How set up Global Helpers in Laravel in 3 easy steps.
2 min readApr 11, 2022
--
In Laravel, Global Helpers are an excellent way for making data or any other functionality available throughout your application with the use of a single function.
In this example I will show you how to set up a custom global helper in 3 easy steps.
Step 1
- Create a folder within your
app
directory calledHelpers
- Create a file called
utility_helpers.php
within theHelpers
directory.
Step 2
- In your
composer.json
file, add a section underautoload
calledfiles
and add yourutility_helpers.php
within that section.
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app\\Helpers\\utility_helper.php"
]
},
Step 3
- Back in your
utility_helpers.php
file, create your functions in which you want to make your data or functionality available throughout your application. - In my example below, I created a simple function that evaluates the
null
status of a variable and returns the inverse. The function is exactly the same as executing the built-in PHP function!is_null($variable)
. In fact it usesis_null
under the hood.
if (! function_exists('notNull')) {
function notNull(mixed $value)
{
return ! is_null($value);
}
}
- I use this
notNull($variable)
function frequently throughout my projects. Although it does not add any additional functionality within my application. It makes code easier to read and looks a lot better than using the built-in function!is_null($variable)
.
Troubleshooting
If you have any issues or getting any errors within your application when working with your custom global helpers, please run composer dump-autoload
in order for composer
to fix any file imports.