Helpers function in Laravel 8 (Global function)

Sometimes we need some helper functions to be accessed from both in controller and views. In this note, the way to add a global helper in laravel 8 is shown. Follow the steps below.

Step 1: create a helper file

You can create it anywhere in your project directory. I prefer to create inside the app folder.

Go to app/ directory and create a file called helpers.php. So, the location would be app/helpers.php

 

Step 2: Write the helper function

Write all your helper functions here. Make sure you check if the function exists. the format would be like this:

 

<?php

if(!function_exists('your_function_name')){
  function your_function_name(){
      // your codes
 }
}

Step 3: Include it in our composer.json

in the value of the “autoload” key, add “files” as a key, with an array as the value, the array will contain “app/helpers.php”.

so your autoload block will be look like this:

“autoload”: {
“psr-4”: {
“App\\”: “app/”,
“Database\\Factories\\”: “database/factories/”,
“Database\\Seeders\\”: “database/seeders/”
},
“files”: [
app/helpers.php
]
}, 

Step 4: Regenerate the list of all classes in the app

Now run “composer dump-autoload”

That is all, we can now call our function anywhere in our app
In view

 <div>
     @php
        $your_function_name = your_function_name();
     @endphp

        {{ $your_function_name }}
 </div>

** In controller**

$your_function_name = your_function_name();