Laravel Facades provide a “static” interface to classes that are available in the application’s service container. Laravel ships with so many facades which provide access to almost all of the Laravel’s features. Laravel facade serves as “static proxies” to underlying classes in the service container. All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace.

use Illuminate\Support\Facades\Cache; Route::get('/cache', function () { return Cache::get('key'); });

Laravel 6 Facades Example

Now, we will take one example to illustrate the Laravel Facade.

First, download the Fresh Laravel. In the app directory, make one folder called Person.

In that folder, create one file called Person.php.

<?php // Person.php namespace App\Person; class Person { public function getName() { return 'AppDividend'; } }

To call this method, we just need to include this file in the routes >> web.php file.

<?php // web.php use App\Person\Person; Route::get('/', function () { $person = new Person(); echo $person->getName(); });

So, here in this example, the Person.php file has one non-static method. So, we have made one object of it and then call the method, and we can see the output in the browser.

Now, change the code like this in the web.php file.

<?php // web.php Route::get('/', function () { Person::getName(); });

Run this in the browser, you will see like this.

“Class ‘Person’ not found.”

So, if you still want the output result like “AppDividend,” then you have to use the Power of Facades.

Facades

In the app directory, create one more folder called, Facades and in that folder, make one file called Person.php.

<?php namespace App\Facades; class Person extends \Illuminate\Support\Facades\Facade { public static function getFacadeAccessor() { return 'name'; } }

Now, we need to map this accessor to our original Person\Person.php class and make its object. That is where the service container is required. We can though write this logic in web.php, or we can create one file called NameServiceProvider.

For this example, we will write this logic in the web.php file.

<?php // web.php app()->bind('name', function() { return new \App\Person\Person; }); Route::get('/', function () { return Person::getName(); });

Here, we are binding the facade accessor to the original class, on which we need to create an object. So behind the scenes, we are newing up the instance and call its method.

Also, we need to add aliases in the config >> app.php file.