Enter your keyword

Creating custom global helper functions in Laravel

Creating custom global helper functions in Laravel

Laravel comes with many helper functions that you can use straight out of the box. But once in a while you find the need to extend such helper functionality with your own custom functions.
But make sure the custom functionality you need to implement is not already available in the standard language (PHP) library and in Laravel framework.

I will take you through the simple steps to achieve this…

Create the helper file

Borrowing from Laravel directory structure, I prefer to put my helper file at app/Support/helper.php

Register helper file with Composer: composer.json

Composer has the ability to auto-load files so that they are accessible on every request in your application.

After registering your helper file, you need to update the auto-loader so that our helper class can be auto loaded on every request.
composer dump-autoload

Create your first helper function

Now lets create our first helper function


Let’s test via Tinker, or any where in your controllers…

In your Blade views

<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:

And use any where in your views as follows…

Note: you might need to clear cached views
php artisan view:clear

That’s it. You’ve written your first global Laravel helper, cheers…
Hope this helps someone someday. Don’t hesitate to contact me if your need more guidance…