How To Create a Global Helper Functions in Laravel 8?

How To Use Helper Functions in Laravel 8

Many times, we need to perform certain tasks over and over again, across multiple files (controllers & blade) files in a Laravel project. Laravel provides a very simple and efficient way to use global functions. Known as helper functions in Laravel, these global functions are accessible from anywhere within the project folder.

Let’s see how to use the helper functions in Laravel 8?

How To Add Helper Functions in Laravel 8?

The steps to add helper functions via a helper file can be listed below:

  • Create a Helpers folder under the app directory of your project.
  • Create a helpers.php file inside the Helpers directory.
  • Add your helper functions inside the helpers.php file.
  • Add path to the helpers.php file in the composer.json file.
  • Run composer dump-autoload
  • Start using the helper functions in your code

Step 1: Create the helper file.

As the first step, go to the app folder of your project and create a new folder called Helpers. Then, go inside this folder and create a helpers.php file.

create new helpers file
Create helpers.php under Helpers folder under the app folder

Step 2: Create your helper functions

Now that you have your helper file in place, write your helper functions inside the helpers.php file. Please note that the functions here should not have any scope declaration. Valid examples are in the screenshot below:

helper functions in php laravel
Write your helper functions inside the helpers.php file

Step 3: Update composer.json file

With the helper file and functions in place, we need to now tell Laravel about it. To do that, open your composer.json file and add the below code inside autoload and save it.

"files": [
            "app/Helpers/helpers.php"
        ]
add helpers file in composer
Add helpers file in composer.json

Step 4: Run composer dump-autoload

Once the composer.json file is added. we need to reload stuff. To do that, go to your terminal and type the following:

composer dump-autoload
Runc composer dump-autoload to reload the updated composer.json file
Run composer dump-autoload to reload the updated composer.json file

Step 5: Start using the helper functions

With composer dump-autoload done, we can now use the helper functions. Please note that Laravel helper functions are available inside both the controllers and blade files. This is how we can use them.

helper functions in php laravel
Write your helper functions inside the helpers.php file

That’s it!

Share This Post

1 thought on “How To Create a Global Helper Functions in Laravel 8?”

  1. Pingback: How To Install SSL Certificate on AWS LightSail using bncert-tool? - Rajiv Verma

Leave a Comment

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

Subscribe To my Future Posts

Get notified whenever I post something new

More To Explore