Laravel Custom Helper Functions

How to Create Custom Helper Functions in Laravel

Spread the love

Last Updated on March 2, 2023

One of the key-feature of laravel is its inbuilt helper functions. These functions help speed up the development process. Helper functions such as env(), config(), and dd() have become the norm in Laravel and we use them on a daily basis.

As much as Laravel has a lot of inbuilt helper functions, sometimes the built-in helper functions are not enough to meet your needs. In such cases, it’s important to know how to create custom helper functions in Laravel.

In this article, we’ll explore the process of creating custom helper functions in Laravel, including why they are beneficial, how to create them, and an example of a custom helper function and how to use it in your own projects.

Let’s get started.

What are Helper Functions?

In Laravel, helper functions are essentially reusable code snippets that can be used throughout your application. These functions are designed to simplify common tasks and reduce code duplication, making your code more readable and easier to maintain.

Benefits of creating custom helper functions in Laravel

There are several benefits of creating custom helper functions in Laravel:

  • Code reusability: Custom helper functions can be used multiple times throughout your application, reducing the amount of code duplication and making your code more maintainable.
  • Improved readability: They can make your code more readable and easier to understand. By abstracting complex code into a single function with a descriptive name, you can convey the purpose of the code more effectively
  • Flexibility: They give you more control over how your application works. By creating your own functions, you can tailor them to your specific needs and make your application more efficient.
  • Code organization: These functions can help keep your code organized by separating it into logical functions with distinct responsibilities. This can make your code more modular and easier to read.

Creating Custom Helper Functions in Laravel

We can follow these steps to create custom helper functions.

Create a Helpers Folder and a helper file.

We will first need to create a helper file that will contain all our helper functions. I will create my Helper Folder in the App Path. (App\Helpers\helpers.php)

Create a ServiceProvider

We will then need to create a service provider where we can register the helper files.

php artisan make:provider HelperServiceProvider

In the register method of the service provider, we will register all helper files for the application.

//App/Providers/HelperServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $files = glob(app_path('Helpers') . "/*.php");
        foreach ($files as $key => $file) {
            require_once $file;
        }
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //
    }
}

Here, we are using the glob() php helper to specify the pathnames for the helper files. We are matching all files with a .php extension as a helper file.

We then include the files as part of laravel and when the application boots, the helper files with all the helper functions are registered into the app container.

The next step is to register the ServiceProvider in the config/app.php file.

//config/app.php
<?php

...

'providers' => [
   App\Providers\HelperServiceProvider::class,
],

...

Defining the helper functions

Now that our helper files have been “bootstrapped”, we can now create our helper functions.

In the App\Helpers\helper.php file, I can now add my custom helper functions

I will create a simple helper function that will upload files.

//App/Helpers/helper.php

<?php

use Illuminate\Support\Str;
use Illuminate\Http\UploadedFile;

if (!function_exists('UploadFile')) {
    /**
     * This function uploads files to the filesystem of your choice
     * @param \Illuminate\Http\UploadedFile $file The File to Upload
     * @param string|null $filename The file name
     * @param string|null $folder A specific folder where the file will be stored
     * @param string $disk Your preferred Storage location(s3,public,gcs etc)
     */

    function UploadFile(UploadedFile $file, $folder = null, $filename = null, $disk = 's3')
    {
        $name = is_null($filename) ? $filename : Str::random(10);

        return $file->storeAs(
            $folder,
            $name . "." . $file->getClientOriginalExtension(),
            $disk
        );
    }
}

I am using the function_exists() helper to ensure that the function will only be available if it does not exist in the application instance.

With that, the function is available globally in my Laravel Application. I can now use it anywhere I want.

Using the function

I will create a controller and use the function.

php artisan make:controller FileController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileController extends Controller
{
    public function upload(Request $request)
    {
        $file_path = UploadFile($request->file('file'), 'Products'); //Using my Custom Helper Function to Upload Files
    }
}

As you can see, I am using my own custom helper function within the controller to upload files to my Amazon S3 Bucket.

You can now create as many helper functions as you like and boost your productivity when developing with Laravel.

Conclusion

Custom helper functions allow us to create reusable snippets of code and make our code more efficient, organized, and maintainable.

By creating your own functions, you can streamline development, reduce code duplication, and make your code more readable and modular. Additionally, helper functions give you more control over how your application works, allowing you to tailor your code to your specific needs and make your application more efficient.

I hope this article has provided valuable insight into how to create custom helper functions and inspired you to create your own custom helper functions. If you enjoyed this article, you will definitely enjoy other articles I have written in this blog.

Thank you for reading.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *