In this article I will show you how to create your own custom helpers in Laravel framework.
Create Project
Run the following composer command to create a new Laravel project:
1
| |
Customer Helpers’ Dir
Customer helpers files will be located in the app dir.
Create a new directory Helpers in app/Helpers
Define Helper Class
Let’s create a simple helper function that will return the user’s full name format.
Create a new file UserHelper.php in app/Helpers and add the following codes:
1 2 3 4 5 6 7 8 9 | |
- namespace App\Helpers;: defines the Helpers namespace.
- public static function full_name($first_name, $last_name) {...}: defines a static function which return the user’s full name.
Helpers Service Provider Class
Service providers are used to auto load classes in Laravel framework.
We will need to define a service provider that will load all of our helpers classes in app/Helpers directory.
Run the following artisan command to create HelperServiceProvider.php in app/Providers directory:
1
| |
And then add the following code below in HelperServiceProvider.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
- namespace App\Providers;: defines the namespace provider.
- use Illuminate\Support\ServiceProvider;: imports the ServiceProvider class namespace.
- class HelperServiceProvider extends ServiceProvider {...}: defines a HelperServiceProvider class that extends/inherite the ServiceProvider class.
- public function register() {...} is the function that is used to loads the helpers.
- foreach (glob(app_path().'/Helpers/*.php') as $filename) {...}: loops through all the files in app/Helpers directory and loads them.
Configure Helper Service Provider and Class Alias
We need to register the HelperServiceProvider and create an alias for the helpers.
Open up config/app.php file and add the following line in providers array variable.
1
| |
And then add the following line in aliases array variable.
1
| |
Using the Custom Helper
Let create a route that will the custom helper function. Open up routes/web.php and add the following codes:
1 2 3 | |
- return UserHelper::full_name("Bunlong", "Van"); calls the static function full_name in UserHelper class.
Open up your browser and type the uri http://localhost:8000/users you will see “Bunlong, Van” text.
So far so good, That’s it!!! See ya!!! :)