Helpers are built-in functions that we can call from anywhere in the laravel project. Helpers are global functions that can be called in controller method and as well as in views without importing class of a method. We can create our own helper classes. You can create helpers anywhere in the app folder depending on your choice.
Here are my two chosen directory locations.
Step 1: Create a helper file
Go to /app/Helpers and create file helper.php
Step 2: Write the helper function
Step 3: Include helper file in our composer.json
To load our file having helper functions we need to add it in the files array of the autoload object inside the composer.json file as shown below. It will load the file on bootstrapping of the application.
After adding your file in the composer.json file run the following:
Now on every request, the helper.php file will be loaded automatically because Laravel requires Composer’s autoloader in public/index.php.
Use of helper method in the controller