One of the questions that comes up often in forums, and one I am asked most by email, is where to put custom functions added to a Laravel project.
Although there are many places they could go, the most popular approach is the one described below.
Inside your project's app directory, create a file named helpers.php and add your functions to it.
Then edit your composer.json file as follows:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files\\": [
"app/helpers.php"
]
},
This adds your file to the files Composer autoloads. To activate autoloading, run the following command in the console/terminal/command prompt you use, from your project's root directory.
$ composer dump-autoload -o
With the -o option (—optimize for short), we tell Composer to also optimize the generated autoload file.
You can now use your helper functions anywhere in your Laravel project.
Happy Laravel coding!