Skip to main content
Category:

Custom Facades provide a static interface to a class that gives access to an object from the service container, let’s look at Laravel’s Custom Facades.

You can define a facade simply by using getFacadeAccessor method for a facade class.

In this post will create a custom facade in Laravel by following below few short steps.

  1. Create a PHP class file
  2. Bind that class to Service Provider
  3. Register that Service Provider in Config\app.php
  4. Create a class that extends Illuminate\Support\Facades\Facade
  5. Register your facade in Config\app.php as aliases

So let’s get started to create an awesome facade.

 

Step 1: Create Check.php Class

In Following step, first you should create "Repositories" directory in app folder and create file Check.php. Now copy the following code in your Check.php file.

app/Repositories/Check.php

namespace App\Repositories;

class Check
{
    public function test()
    {
        dd("Hello Artisan");
    }
}

 

Step 2: Create Our Own ServiceProvider

In this step you should create service provider for bind class, so fire your terminal or cmd this following command:

php artisan make:provider CustomFacadesProvider

 

Ok, now you can find new file CustomFacadesProvider.php in your providers(app/Providers) directory and paste this following code.

app/Providers/CustomFacadesProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class CustomFacadesProvider extends ServiceProvider
{
   
    public function register()
    {  
        app()->bind('check', function(){  //Keep in mind this "check" must be return from facades accessor
            return new \App\Repositories\Check;
        });
    }

}   

 

Step 3: Create Facade Class

In this step create another class in our Repositories directory called TestFacades.php In this class you have to extend "Illuminate\Support\Facades\Facade" class, copy and paste this following code.

app/Repositories/TestFacades.php

namespace App\Repositories;

use Illuminate\Support\Facades\Facade;

class TestFacades extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'check';
    }
}

 

Step 4: Register Service Provider

Now register our provider and facades in the following path

config/app.php

// In providers array
App\Providers\CustomFacadesProvider::class,


 

And also add aliase for facade in this file like this way :

'Demo' => App\Repositories\TestFacades::class,

 

 

Step 5 :  Create Route

Now we can access our Check.php class method with scope resulation via Demo facades aliase. Now just check it after visiting this route url.

Route::get('demo', function(){

    Demo::test();

});
 

Hope you enjoyed this tutorial. Hope it can help you.

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook