How to Create Custom Facade in Laravel 7


How to Create Custom Facade in Laravel 7
13
Oct

Sometimes we use repeat code and repeatedly use the function at that time we can create a custom facade for our project, that way you can create functions and use them. In this post will create a custom facade in Laravel by following below few short steps. So let's start our Laravel 7 custom facades tutorial.

 

Step 1: Create Helper.php Class

In the Following step, first, we need to create the "Repositories" directory in the app folder and create the file Helper.php. Now copy the following code in your Helper.php file.

app/Repositories/Helper.php

<?php

namespace App\Repositories;

class Helper
{
    public function test()
    {
        dd("Customer Helper using Facade");
    }
}

 

Step 2: Create Own ServiceProvider

In this step you should create a service provider for bind class, so open your terminal or cmd  and write the following command:

php artisan make:provider HelperFacadesProvider

 

Now you can find the new file HelperFacadesProvider.php in your providers(app/Providers) directory and paste the following code:

app/Providers/HelperFacadesProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperFacadesProvider extends ServiceProvider
{


    public function boot()
    {
      //
    }
   
    public function register()
    {  
        app()->bind('helperFacade', function(){  //Keep in mind this "helperFacade" must be return from facades accessor
            return new App\Repositories\Helper;
        });
    }



}

 

Step 3: Create Facade Class

In this step create another class in our Repositories directory called HelperFacades.php In this class you have to extend "IlluminateSupportFacadesFacade" class, copy and paste the following code.

app/Repositories/HelperFacades.php

<?php

namespace App\Repositories;

use Illuminate\Support\Facades\Facade;

class HelperFacades extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'helperFacade';
    }
}

 

Step 4: Register Service Provider

Now register our provider and facades in the following path.

config/app.php

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

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

'Helper' => App\Repositories\HelperFacades::class,

 

Step 5 :  Test Facade in Route

Now we can access our Helper.php class method with scope resolution via Demo facades aliased. Now just check it after visiting this route URL.

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

    Helper::test();

});
 

 

After visiting this route url, you should see the following output.

Custom Facades

"Customer Helper using Facade"

 


Login   To Comment & Like

Comments