twitter github codepen dribbble rss

Create Laravel Facades Quickly with Realtime Facades

Aside from using global functions, you can use Laravel Facades to create your own helper functions. Normally, you need to create three classes when making custom Laravel Facade. First one is the main class which is the place to put all of your custom functions. The other two are a Service Provider class and a class that extend Illuminate\Support\Facades\Facade.

In Laravel 5.4, you don’t really need to create all of those three classes anymore because it has a new feature called Realtime Facades. Basically, you only need to create one class now which is your main class that contain all of your custom functions. And add Facades namespace in front of your class full name whenever you’re referencing it.

For example, I have a custom class called Helpers. You can place it in any folder. I always create a new folder called Classes or Helpers under my app folder and place it in there.

<?php

namespace App\Classes;

class Helpers  {
    
    public function siteTitle()
    {
        return 'Something';
    }

}

In order to make that class as a facade you need to reference it with the Facades namespace in front of its name as if it resides in Facades namespace.

use Facades\App\Classes\Helpers;

And then you can call its function like this :

echo Helpers::siteTitle();

You can also make an alias for your facade in config/app.php.

'Helpers' => Facades\App\Classes\Helpers::class,

So that you won’t need to type a long name when you use it in your blade template.

<title>{{ Helpers::siteTitle() }}</title>

This new Realtime Facades is really make the creation of Laravel Facades much simpler. Of course, you can still use the normal way when creating Laravel Facades if you want to.