Posts Learn Components new Snippets new Categories Tags About
/

Best Practices for Custom Helpers in Laravel 8

Learn how to define custom helpers and the best practice you can follow for you Laravel 8 project

Created on Sep 23, 2021

•

70 views

In this snippet, you will learn how to define custom helpers that will be available throughout your Laravel application and the best practice that you can follow to define it.

Step 1: Create helpers.php file inside the app folder


The first method is to create a custom "helpers.php" from within the "app/" folder and place all of the functions inside the file.
app/helpers.php

Step 2: Reference from composer.json


Now that the helpers.php file has been defined, you can include the files from the composer.json file to autoload it. Do note that you need to reference it from within the "files" key inside the "autoload".
// composer.json

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php" // <---- Add the helper file
    ]
},

Step 3: Run autoload command


Now that you have it defined, you can call the composer autoload command.
composer dumpautoload
or if you prefer having the dash "-" it will be like below.
composer dump-autoload

Another Approach


If you might not want the helper file to be created directly under the "app" folder then you can create a dedicated folder called "Helpers". Having a custom "Helpers" folder will allow you to create more helper files. Let's say you have 2 different helpers files and it's called "string-formatting.php" and "number-formatting.php", you can define the file like below.
"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Helpers/string-formatting.php", // <---- Add this helper file
        "app/Helpers/number-formatting.php" // <---- And this helper file
    ]
},

Conclusion


By now you should be able to define a custom helper for your Laravel project that's accessible from anywhere within the codes and how to autoload it using composer. If you find this snippet to be helpful do make sure to share it with your friends and cheers. If you have any feedback do start a new discussion from the comment box below.
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻