Step by step guide to create a custom facade in Laravel 5.4.
In your App directory of Laravel create a new folder "Classes". In "Classes" directory Create a new php file Sampleclass.php
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
Step 3. Creating a Facade class- Create PHP Class File.
- Bind your class to service provider by creating a service provider class.
- Create a Facade class
- Register your service provider in providers array and facade class in aliases array of app/config.php
In your App directory of Laravel create a new folder "Classes". In "Classes" directory Create a new php file Sampleclass.php
<?php
//importing name space
namespace App\Classes;
class Sampleclass {
public function dumpData($array = [])
{
dd($array)
}
}
?>
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 \App\Classes\Sampleclass;
});
Navigate to App\Facades 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)
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class sampleFacade extends Facade{
protected static function getFacadeAccessor() {
return 'Sampleclass';
}
}
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
App\Providers\SampleclassServiceProvider::class,
//Registering your facade class Add below code in aliases array
'sampleFacade' => App\Facades\sampleFacade::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
$array=['1','2','3'];
sampleFacade::dumpData($array);
Top 20 Laravel Interview Questions and answers for Experienced
No comments