Laravel — Include your own helper functions

Dennis Smink
2 min readApr 16, 2019

Sometimes you might want to create a function that is available everywhere, this is where this tutorial comes in handy for you 👏

Everywhere I look I see tutorials passing by where they explain that you can achieve this easily by adding an autoload file to your composer file. For some reason I think its quite ugly and can get un-readable as your helpers.php might grow in that case.

I have been using a method for a long while where you are able to declare several files which contain methods, this is much cleaner and more read-able.

Let’s start.. 🔥

First of start by making a HelperServiceProvider.php provider:

php artisan make:provider HelperServiceProvider

Once you’ve done this you will see a new file inside app\Providers called HelperServiceProvider.php

You can safely remove the complete boot() method as we are not going to use this.

Inside the register function enter this piece of code:

public function register()
{
foreach (
glob(app_path('Helpers') . '/*.php') as $file) {
require_once
$file;
}
}

What this does is loop through all the files inside app/Helpers, you might of guessed it already: You can now enter several PHP…

--

--