How to create custom helper functions in Laravel 5?

By | March 10, 2018

From the laravel official
Laravel includes a variety of global "helper" PHP functions. Many of these helper functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.

Helpers are pre built utility functions in laravel which we can use directly without any class import/extend. e.g. str_random() – generates a random string of the specified length.
dd() – dumps the given variables and ends execution of the script.

We can also create our own helpers in laravel. Here are the steps.

Step1 : Create a folder in app folder with named Helpers(You can create with other name also).
Step2 : Now create a file with name helpers.php(You can create with other name also) file in Helpers folder
Step3 : Add the utility functions in that file.
Step3 : Now add the open composer.json locate autoload block and add the following line

"files": ["app/Helpers/helpers.php"]

Step3 : Now,load it up with composer – composer dump-autoload

Now you can use your utility functions anywhere in the application.

Leave a Reply

Your email address will not be published. Required fields are marked *