Creating custom facade in Laravel 5

Creating custom facade in Laravel 5

Step by step guide to create a custom facade in Laravel 5.

  1. Create PHP Class File.
  2. Bind your class to a service provider by creating a service provider class.
  3. Create a Facade class
  4. Register your service provider in providers array and facade class in aliases array of app/config.php

Step 1. Creating a PHP Class.
In your App directory of Laravel create a new folder “Classes”. In “Classes” directory Create a new php file Sampleclass.php

Step 2.Creating a service provider class and binding our class.
Creating service container class via php artisan command. Navigate to app/Providers folder and run below command php artisan make:provider ‘SampleclassServiceProvider’ Binding our class to service provider. In register() method /function of SampleclassServiceProvider class Add below code

 App::bind('Sampleclass', function(){
 // creating and returning object of our class
           return new AppClassesSampleclass;

Step 3. Creating a Facade class
Navigate to AppFacades Directory and create a new file “sampleFacade.php” and add below code (Please create new directory “Facades” if it does not exists in App folder)

Step 4. Registering your service provider in providers array and Facade class in aliases array of app/config.php//Registering your service provider
Open config/app.php and add below line in providers array


//Registering your facade class
Add below code in aliases array

'sampleFacade'       => AppFacadessampleFacade::class

Congrats you have successfully created and configured your custom Facade in Laravel You can use your Facade any where in project by using below code


Top 20 Laravel Interview Questions and answers for Experienced

Leave a Reply

Your email address will not be published. Required fields are marked *