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
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.
Leave a reply