How To Create A Global Helper Functions In Laravel 8?

How To Create A Global 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.jpg

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:

add helper functions in the helpers file.jpg

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-1024x272.png

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

run composer-dumpautoload.jpg

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.

use helper function.jpg

That’s it!

You can read the original article here - rajivverma.me/blog/tech/global-helper-funct..