Home / Snippets / Best Practices for Custom Helpers in Laravel 8
Best Practices for Custom Helpers in Laravel 8 cover

Best Practices for Custom Helpers in Laravel 8

874

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this