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 do helper_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?
Create a new file in your app/Helpers directory name it AnythingHelper.php An example of my helper is :
generate a service provider for your helper by following command
in the register function of your newly generated HelperServiceProvider.php add following code
now in your config/app.php load this service provider and you are done
Another 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 it insideapp/Helpers
.Add your functions, but do not add a class or namespace.
In
composer.json
inside theautoload
section add the following line:For Laravel 5:
composer dump-autoload
Congratulations! You may now access
global_function_example('hello world')
form any part of your application including Blade views.I hope this is useful for someone!
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 ofHelper::greeting('Brian');
just like Laravel does with their helpers.File:
app/Support/helper.php
Register helper file with Composer:
composer.json
Create your first helper function
Usage:
Remember to autoload the file before trying to access its functions:
composer dump-autoload
Let's test with Tinker
With Blade
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
Usage:
<p>@greet('Brian')</p>
Note: you might need to clear cache views
php artisan view:clear