Sometimes you might want to create a function that is available everywhere, this is where this tutorial comes in handy for you ?
Everywhere I look I see tutorials passing by where they explain that you can achieve this easily by adding an autoload file to your composer file. For some reason I think its quite ugly and can get un-readable as your helpers.php might grow in that case.
I have been using a method for a long while where you are able to declare several files which contain methods, this is much cleaner and more read-able.
Let’s start.. ?
First of start by making a HelperServiceProvider.php provider:
php artisan make:provider HelperServiceProvider
Once you’ve done this you will see a new file inside app\Providers called HelperServiceProvider.php
You can safely remove the complete boot() method as we are not going to use this.
Inside the register function enter this piece of code:
public function register()
{
foreach (glob(app_path('Helpers') . '/*.php') as $file) {
require_once $file;
}
}
What this does is loop through all the files inside app/Helpers, you might of guessed it already: You can now enter several PHP files in that directory (which you might need to create) which will be loaded into your application. These helper functions are available in each part of your code (views, models, controllers etcetera)
We still need to load this provider, open up config/app.php and add the HelperServiceProvider above your AppServiceProvider:
...App\Providers\HelperServiceProvider::class,
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,...
Now lets try to create a simple function, create a new file called Carbon.php inside app/Helpers folder with these contents:
<?php
/**
* Carbon helper
*
* @param $time
* @param $tz
*
* @return Carbon\Carbon
*/
function carbon($time = null, $tz = null)
{
return new \Carbon\Carbon($time, $tz);
}
You do not need to enter any namespacing. And if you want, you can check if the function exists by calling an if statement function_exists which might be a good idea.
You can now use the helper carbon() everywhere in the application you’d like. Now lets say if you need another function that is returning a specific format (just for the use-case of this tutorial) you can just enter that in the same file (Carbon.php):
<?php
/**
* Carbon helper
*
* @param $time
* @param $tz
*
* @return Carbon\Carbon
*/
function carbon($time = null, $tz = null)
{
return new \Carbon\Carbon($time, $tz);
}function carbonFormatted($time = null, $tz = null)
{
return carbon($time, $tz)->format('Y-m-d')
}
Thats it! You can now start filling up the app/Helpers directory with your own PHP files which contain quick helpers that you use often ?