Laravel 10/9,8,7,6 create custom facade example; Through this tutorial, i am going to show you how to create and use custom facade in Laravel 10/9,8,7,6 apps.
Laravel Create Custom Facade Class Example
Use the below steps to create and use custom facade class in Laravel 10/9,8,7,6 apps:
- Step 1 – Create a PHP class file
- Step 2 – Bind that class to Service Provider
- Step 3 – Register that Service Provider in
Config\app.php
- Step 4 – Create a class that extends Illuminate\Support\Facades\Facade
- Step 5 – Register your facade in
Config\app.php
as aliases
Step 1 – Create a PHP class file
To create a PHP helper class LaraTutorials.php
inside App
. Can create a folder of your own choice instead of LaraTutorials.
namespace App\LaraTutorials; class LaraTutorials { public function sayHello() { echo "Hello, from Facade class."; } }
Step 2 – Bind that class to Service Provider
Run the following command on on command prompt to create service provider:
php artisan make:provider LaraTutorialsServiceProvider
Bind this class to a Service Provider. Then add below code in register
method for binding our class:
$this->app->bind('laratutorials',function(){ return new LaraTutorials(); });
Now, your service provider class will look like below:
namespace App\Providers; use App\LaraTutorials; use Illuminate\Support\Facades\App; use Illuminate\Support\ServiceProvider; class LaraTutorialsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind('laratutorials',function(){ return new LaraTutorials(); }); } }
Step 3 – Register that Service Provider in Config\app.php
To register that service provider in config\app.php
as providers:
/* * Application Service Providers... */ App\Providers\LaraTutorialsServiceProvider::class,
Step 4 – Create a class that extends Illuminate\Support\Facades\Facade
To create a file LaraTutorialsFacade
in App\LaraTutorials
which will extend Illuminate\Support\Facades\Facade
. in our example, class will look like below.
namespace App\LaraTutorials;
use Illuminate\Support\Facades\Facade;
class LaraTutorialsFacade extends Facade { protected static function getFacadeAccessor() { return 'laratutorials'; } }
Step 5 – Register your facade in Config\app.php
as aliases
To register class created in Step 4 in config\app.php
as aliases:
'LaraTutorials' => App\LaraTutorials\LaraTutorialsFacade::class
Test This Facade
Let’s test your facade by adding a simple route which will resolve to a closure function implementing our facade class.
Route::get('/laratutorials', function() { LaraTutorials::sayHello(); });
Visit your browser with the above route and you will see the hello message.
Conclusion
Laravel create custom facade example. In this tutorial, you have learned how to create and use custom facade in laravel 6, 7, 8 app.
Be First to Comment