How to create custom helper functions in Laravel

The Laravel framework includes numerous helpful utilities in the form of classes, directives, or simple functions. While developing applications, everyone has encountered at least one of them.

Custom helper functions are useful for tasks like data formatting, working with arrays and files, error handling, validation, and much more.

For example, Laravel incorporates the VarDumper package in its core, which includes functions like dd and dump for testing and debugging. Other helpful functions include route, config, request, and more. Developers love these because they simplify the code.

To better understand what Laravel is capable of, spend some time reading the documentation on all available helper functions: Laravel Helpers Documentation. This package can be used not only in Laravel projects but also in any other PHP project by simply adding it to your composer dependencies:

composer require laravel/helpers

However, sometimes the framework's built-in functionality isn't enough, and that's when the need to create your own custom functions arises-either for business-specific requirements or internal developer needs.

If your recent projects have repetitive logic, it might be a good idea to move those code segments into a separate file for reuse. Save precious time-time better spent enjoying a cup of coffee.

In this article, we'll explore how to create custom helper functions in Laravel.

Benefits of Custom Helper Functions

Creating custom helper functions in Laravel comes with several advantages:

  • Eliminates Code Duplication: Helper functions help encapsulate repetitive code into reusable segments.
  • Improves Code Readability: Reusing functions reduces the number of written lines, making the code easier to read, understand, and maintain.
  • Enhances Code Structure: Helper functions help organize code, making it more logical and modular.

Creating Helper Functions via Composer

To create a helper function, you'll need to create a file and register it with Composer. It's common to place custom functions in directories like app, app/Http, bootstrap, or even at the project root, but the choice is yours.

Steps to Create Helper Functions:

  1. Create a File

Create a file named bootstrap/functions.php and add your custom function:

if (!function_exists('cowsay')) {
    function cowsay(string $say_message = 'Hi, welcome'): void
    {
        echo <<<DOC
        {$say_message}
            \   ^__^
             \  (oo)\_______
                (__)\       )\/\
                    ||----w |
                    ||     ||
        DOC;
    }
}
  1. Register the File in composer.json

Add the bootstrap/functions.php file to the autoload.files section in your composer.json. If it doesn’t already exist, add it as shown:

"autoload": {
    "files": [
        "bootstrap/functions.php"
    ]
}
  1. Update Composer Autoloader

Run the following command to refresh the autoloader:

composer dump-autoload

Now, your functions.php file will be automatically loaded with every request. The example above shows how to create a simple helper function to display a message for your friends.

Creating Helper Functions via Service Provider

Service providers are an excellent place to register your custom functions. By including a provider in the application load process, you ensure the functions are always defined.

Steps to Register Functions via ServiceProvider:

  1. Create a Provider

Create a provider named HelperServiceProvider.php either manually or by running:

php artisan make:provider HelperServiceProvider

class HelperServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $files = glob(app_path('Support') . "/*-helper.php");
        foreach ($files as $file) {
            require_once $file;
        }
    }
}
  1. Create a Directory for Functions

Create a directory for your functions, such as app/Support.

  1. Add Logic to a File

Create a file with the function logic, for example, app/Support/path-helper.php.

  1. Register the Provider

Add the new provider to AppServiceProvider or register it in providers.php (for Laravel 11) or config/app.php (for earlier versions).

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->register(HelperServiceProvider::class);
    }
}

Now you can start using the function in your project.

Autoloading Functions in Laravel 11 Core

If you check the Laravel core, you'll see that all built-in helper functions are loaded via Composer's autoloader. You can follow the same approach for your custom functions by registering them in composer.json.

"autoload": {
    "files": [
        "src/Illuminate/Collections/functions.php",
        "src/Illuminate/Collections/helpers.php",
        "src/Illuminate/Events/functions.php",
        "src/Illuminate/Filesystem/functions.php",
        "src/Illuminate/Foundation/helpers.php",
        "src/Illuminate/Log/functions.php",
        "src/Illuminate/Support/functions.php",
        "src/Illuminate/Support/helpers.php"
    ]
}

Conclusion

Whether you create custom functions via Composer or a Service Provider is up to you, but the Composer method is more convenient and easier for others to understand. So, we recommend using Composer.

When calling APIs or returning responses to clients, you may unknowingly rely on helper functions. These functions simplify code, make it more readable and maintainable, and align well with the DRY principle. Use them wisely to streamline your development process.

Similar Articles