How to use custom helper file in laravel 5
To avoid repeating some code anywhere in our project we can practice custom helper files. In these helper files, we are using lots of functions that we are not repeating in our code.
In laravel 5 style we are using the same mechanism to do that. Just creating some functions in our helper files and use multiple times in anywhere like the blade template or controller.
First of all, we have to create a directory named Helpers under the apps directory.
[app/Helpers]
Under this Helpers directory, you can create lots of helper files. For testing, we have created one file named library.php. You can create multiple helper files as you like.
[app/Helpers/library.php]
[app/Helpers/anyNameOfFile.php]
Then in the library.php file, we want to create the common functions that we will use lots of time in our project.
In [app/Helpers/library.php]
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php /** * Convert any number to decimal format with thousand separator * @param int $number * @return decimal format number */ public function myNumberFormat($number) { return number_format($number, 2, '.', ','); } ?> |
In this library.php file, we have created a function named myNumberFormat with one argument and that is a number. This function will convert that number to decimal number like 376886 to 376,886.00
So now our helper file is ready. Now we have to add it with laravel functionality for using it anywhere of laravel. For that, we have to add this helper file in the composer.json file
Within composer.json, in the autoload block, just have to add
1 2 3 4 |
"files": [ "app/Helpers/library.php", "app/Helpers/anyNameOfFile.php" ] |
After that just run composer dump-autoload in your project directories terminal. Now your helper files functions named myNumberFormat is completely ready to use anywhere of laravel project.
Uses in anywhere of laravel
In any controller like app/Http/Controllers/HomeController.php you can use like that
1 2 3 4 5 6 7 8 9 10 |
<?php namespace App\Http\Controllers; public function index() { $myBalance =376886; echo "MY BALANCE IS : " .$myBalance. " USD"; // MY BALANCE IS : 376886 USD echo "MY BALANCE IS : " .myNumberFormat($myBalance). " USD"; // MY BALANCE IS : 376,886.00 USD } |
In any blade template file like resources/views/home.blade.php you can use like that
1 |
{{ myNubmerFormat(376886) }} |
So practicing custom helper files, you can easily reduce repeating code from your project.
Recent Comments