How to Create Global Helper Functions, Classes, and/or variables in Laravel

June, 7 2020 PHP Laravel

Sometimes, you will stumble on some functionalities that will be required in so many different parts of your application, then will wonder why you have to keep duplicating this same lines of codes instead of implementing it once and having it reused.

This article shows the steps to achieve that ...

Create a folder Helpers in your Laravel app directory.

mkdir app/Helpers

Create your helper file in your Laravel app\Helpers folder and give it any name of your choice, we will call the file helper.php in this article.

touch app/Helpers/helper.php

Load the file app/Helpers/helper.php up in your composer.json file.

"autoload":{
  "classmap":[
    ...
  ],
  "psr-4":{
    "App\\": "app/"
  },
  "files": [
     "app/Helpers/helper.php" // <---- ADD THIS
  ]
},
    

After adding that to your composer.json file, run the following command:

composer dump-autoload

And that is it, you can declare your functions, classes and/or variables within the helper.php file and it will be available for use in all controllers, views and models.

Thoughts

I'd love to hear your thoughts. Let me know in the comments section on twitter or on LinkedIn


By Nuhu Ibrahim

Full Stack Web and Desktop Developer