Category Archives: Facade in Laravel

Facade in Laravel


What is Facade

Facades provide a “static” interface to classes that are available in the application’s service container(managing class dependencies and performing dependency injection(class dependencies are “injected” into the class via the constructor or, in some cases, “setter” methods.) ).

Laravel facades serve as “static proxies” to underlying classes in the service container, providing the benefit of a short, expressive syntax while maintaining more flexibility(In terms of configuring class/libraries being used) than traditional static methods.

All of Laravel’s facades are defined in the Illuminate\Support\Facades namespace.

How Facades Work

In a Laravel application, a facade is a class that provides access to an object from the service container. The machinery that makes this work is in the Facade class. Laravel’s facades, and any custom facades you create, will extend the base Illuminate\Support\Facades\Facade class.

The Facade base class makes use of the __callStatic() magic-method to defer calls from your facade to an object resolved from the container.

In the below lines , a call is made to the Laravel cache system. By looking at code, one might assume that the static method get is being called on the Cache class:


use Illuminate\Support\Facades\Cache;

function someMethod(){
    $id = 'abc'; //some key on which data is saved
    $user = Cache::get($id);

//If we look at that Illuminate\Support\Facades\Cache class, you'll see that there is no static method named get:

class Cache extends Facade
     * Get the registered name of the component.
     * @return string
    protected static function getFacadeAccessor() { return 'cache'; }

If we look at that Illuminate\Support\Facades\Cache class, you’ll see that there is no static method named get:

Instead, the Cache facade extends the base Facade class and defines the method getFacadeAccessor(). This method’s job is to return the name of a service container binding.

When a user references any static method on the Cache facade, Laravel resolves the cache binding from the service container and runs the requested method (in this case, get) against that object.