Creating Own Custom Helper in Laravel

Laravel already has built-in functions that we can use in Blade template. But what if you need to use your own custom function? If you are familiar with the composer then it is quite easy to use your own custom helper file.

If we talk to implement something without helper function, there is a @php directive block that you can use to write custom PHP codes. But it’s not a good practice to use @php directive block for repeated tasks. It’s better to create custom functions and use that functions on your blade template.

Where do we create helper file?

It is up to you. If you like to create a file under app directory or creating a separate directory on your root project directory.

Load your custom helper file

If you look into the root directory of your project, there is a composer.json file exists. This composer.json file holds all the dependencies packages information that you are using on your Laravel Project. Scroll down the composer.json file and find the autoload property which looks similar to the below codes.

...
"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "classmap": [
        "database/seeds",
        "database/factories"
    ]
},
...

I have created a file in the app directory with the following path app/helper.php and now we have to add this file path to the composer.json file.

...
"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helper.php"
    ], 
    "classmap": [
        "database/seeds",
        "database/factories"
    ]
},
...

Once you set your helper file path to the compser.json file you have to run the following command to autoload it with your project.

composer dump-autoload