How do I make global helper functions in laravel 5?
Solution 1
Create a new file in your app/Helpers directory name it AnythingHelper.php An example of my helper is :
<?php
function getDomesticCities()
{
$result = \App\Package::where('type', '=', 'domestic')
->groupBy('from_city')
->get(['from_city']);
return $result;
}
generate a service provider for your helper by following command
php artisan make:provider HelperServiceProvider
in the register function of your newly generated HelperServiceProvider.php add following code
require_once app_path('Helpers/AnythingHelper.php');
now in your config/app.php load this service provider and you are done
'App\Providers\HelperServiceProvider',
Solution 2
An easy and efficient way of creating a global functions file is to autoload it directly from Composer. The autoload section of composer accepts a files
array that is automatically loaded.
Create a
functions.php
file wherever you like. In this example, we are going to create in insideapp/Helpers
.Add your functions, but do not add a class or namespace.
<?php function global_function_example($str) { return 'A Global Function with '. $str; }
In
composer.json
inside theautoload
section add the following line:"files": ["app/Helpers/functions.php"]
Example for Laravel 5:
"autoload": { "classmap": [ "database" ], "psr-4": { "App\\": "app/" }, "files": ["app/Helpers/functions.php"] // <-- Add this line },
Run
composer dump-autoload
Done! You may now access global_function_example('hello world')
form any part of your application including Blade views.
Solution 3
Laravel global helpers
Often you will find your self in need of a utility function that is access globally throughout you entire application. Borrowing from how laravel writes their default helpers you're able to extend the ability with your custom functions.
Create the helper file, not class
I prefer to you a file and not a class since I dont want to bother with namespaces and I want its functions to be accessible without the class prefixes like: greeting('Brian');
instead of Helper::greeting('Brian');
just like Laravel does with their helpers.
File: app/Support/helper.php
Register helper file with Composer: composer.json
{
...
"autoload": {
"classmap": [
"database"
],
"files": [
"app/Support/helpers.php"
],
"psr-4": {
"App\\": "app/"
}
},
...
}
Create your first helper function
<?php
if (!function_exists('greet')) {
/**
* Greeting a person
*
* @param string $person Name
* @return string
*/
function greet($person)
{
return 'Hello ' . $person;
}
}
Usage:
Remember to autoload the file before trying to access its functions:
composer dump-autoload
Let's test with Tinker
$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.0.6 ΓÇö cli) by Justin Hileman
>>> greet('Brian');
=> "Hello Brian"
>>> exit
Exit: Goodbye.
With Blade
<p>{{ greet('Brian') }}</p>
Advanced usage as Blade directive:
A times you will find yourself wanting to use a blade directive instead of a plain function.
Register you Blade directive in the boot method of AppServiceProvider: app/Providers/AppServiceProvider.php
public function boot()
{
// ...
Blade::directive('greet', function ($expression) {
return "<?php echo greet({$expression}); ?>";
});
}
Usage:
<p>@greet('Brian')</p>
Note: you might need to clear cache views
php artisan view:clear
Solution 4
The above answers are great with a slight complication, therefore this answer exists.
utils.php
if (!function_exists('printHello')) {
function printHello()
{
return "Hello world!";
}
}
in app/Providers/AppServiceProvider.php add the following in register method
public function register()
{
require_once __DIR__ . "/path/to/utils.php"
}
now printHello function is accessible anywhere in code-base just as any other laravel global functions.
Solution 5
Another option, if you don't want to register all your helper functions one by one and wondering how to register them each time you create a new helper function:
Again in the app/Providers/AppServiceProvider.php add the following in register method
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename) {
require_once($filename);
}
}
Related videos on Youtube
TheWebs
Updated on May 07, 2020Comments
-
TheWebs about 4 years
If I wanted to make a
currentUser()
function for some oauth stuff I am doing where I can use it in a view or in a controller (think rails, where you dohelper_method: current_user
in the application controller).Everything I read states to create a helpers folder and add the function there and then that way you can do
Helpers::functionName
Is this the right way to do this?Whats the "laravel way" of creating helper functions that can be used in blade templates and controllers?
-
Iamzozo over 8 yearsMaybe this will help: stackoverflow.com/questions/28290332/…
-
-
MaXi32 over 8 yearsHow do you use this in blade. Do you need to register facade?
-
Khan Shahrukh over 8 yearsNo, only above mentioned code does it, in your blade file do {{ yourHelperFunction('param') }}
-
MaXi32 over 8 yearsI wish I can call the helper function with Helper::myHelperFunction('param') in blade. It looks nicer. Do you know how to register this ?
-
Khan Shahrukh over 8 yearsI dont think you access facades in blade, and if you can (by tweaking something) I am not sure whether it is a good practice
-
MaXi32 over 8 yearsI added alias/facade in config/app like: 'Helper' => App\Helpers\Helper::class, and I'm able to use the Helper::myHelperFunction('param') in blade.
-
MaXi32 over 8 yearsThank you. Not sure if it isn't good practice. I saw many people use it. It just look nicer than having global function that would clash with the built in PHP function. Like time() function. So, it's the best that we use like this MyHelper::time() in blade;
-
Mike Barwick about 8 yearslol @ looks nicer. Facades are NOT nicer - and in most cases, bad practice to use them.
-
4ndro1d over 7 years
require base_path().'/app/Helpers/AnythingHelper.php';
doesn't work for me with error Failed opening required -
Khan Shahrukh over 7 yearsAnythingHelper.php is just an example, you should replace this with original file name
-
Armesh Singh over 7 years@KhanShahrukh use
require_once base_path().'/app/Helpers/AnythingHelper.php';
If you userequire
phpunit will fail. -
jakub_jo about 7 yearsYou should supply the path as an argument to base_path(). Instead: base_path() . '/my/helper.php'; Better use: base_path('/my/helper.php'). Also app_path() would be more suitable ;)
-
Johnny almost 7 yearsI also need to create a global function where can be called in multiple controller files. This looks simple but what happens when run the command
composer dump-autoload
? Are new files been created? I even deleted the files like composer.json, gulpfile.js as I didn't think they were used at all. -
Arian Acosta almost 7 yearsGreat! Running
composer dump-autoload
would be similar to clearing the composer cache. Basically, it re-evaluates the classes that need to be loaded from composer.json file. Good luck! -
Naveen DA about 6 yearsEfficient method
-
phil about 6 yearsmuch straightforward than the accepted answer. I tried both!
-
realnsleo about 5 yearsLove this implementation. Straight forward and faster!
-
Mahesh.D about 5 yearsIn
Lumen
we have to include in this fashionrequire_once base_path('app').'/Helpers/AnythingHelper.php';
-
DragonFire over 4 yearsIf the item is not last don't forget the comma after "files": ["app/Helpers/functions.php"], and for mac the command will be composer.phar dump-autoload
-
Gjaa almost 4 yearsI had to do a composer dump-autoload for it to work
-
Vipertecpro almost 3 yearsDon't forget to define
public static function
otherwise you will get error, something like thisNon-static method App\Helpers\GlobalHelper::getValueFromGlobalHelper() should not be called statically