Autoloading Global Helpers The Laravel Way

Published February 3, 2022 • 2 mins read

I've had this article in my draft since last year but not the time to publish it. So let me do that now. In this article, I will show you a new way to register your global helper files inside your Laravel applications.

What Are Global Helpers?

What I mean by global helpers is that simple .php file that contains PHP functions you can call from anywhere in your application. When I started out, I learned to auto-load this file from the composer.json file and it feels like I am getting my hands dirty whenever I do that.

Autoloading Global Helpers

Let's say we have a helpers.php file inside our app/ directory, in order to auto load this file, we need to register it inside the boot() method of our app/Providers/AppServiceProvider.php class:

public function boot()
{
    if (File::exists(app_path('helpers.php'))) {
        require_once app_path('helpers.php');
    }
}

That's it, we have successfully made our helper functions available across our Laravel application. Now let's make it better and clean.

Clean Up The Code

The Laravel AppServiceProvider class is usually where we register and boot up a lot of things. In my case, it's always filled up. To clean it up, we need to create a private autoload() method inside the AppServiceProvider class, add our auto-load code snippet and call the autoload() method inside the boot() method. Let me show you.

public function boot()
{
    $this->autoload();
}

private function autoload()
{
    if (File::exists(app_path('helpers.php'))) {
        require_once app_path('helpers.php');
    }
}

With this we can to register more global helper files inside the autoload() method without getting our boot() method "dirty".

That's all for now, now you won't need to get your hands dirty with composer.json when you want to register your global helper files.




Hey, have you tried Litehost lately?

Litehost is my side project which is a shared hosting platform with PHP & Laravel developers in mind. It has Composer, Git & PHP CLI pre-installed on its servers. SSH access is also granted on request. Litehost is pretty affordable. Try it today.