Courses

Design Patterns in Laravel 11

Have you ever used Auth::user() in Laravel? So yeah, that Auth is a Facade. Now, we will explore what ready-made Laravel Facades are and how/why we should create our own Facades.


What are Facades?

First, the definition.

Laravel documentation about Facades is, well, a bit confusing:

Laravel Facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

Wait, what does that mean in human language?

Well, you won't have to know what class is underneath the Facade. You can just call the Auth facade and access methods from the underlying class.


Laravel Facades We Can Use

In Laravel, we can call Auth::user() to retrieve the user from the session.

What we don't see under the hood is that it is a "static proxy" to the Illuminate\Auth\AuthManager class. The AuthManager class has a user() method that returns the user from the session.

Facade makes our experience as developers easier. We only have to remember the Auth Facade, and we get instant static access to the user() method.

Let's quickly compare facade usage with the usage of the class itself to illustrate the difference.

How would it look without Facades?

Creating New Class Instance

use Illuminate\Auth\AuthManager;
 
public function index()
{
$auth = new AuthManager();
$user = $auth->user();
}

Or, a bit shorter, with Dependency Injection.

Using Dependency Injection

use Illuminate\Auth\AuthManager;
 
public function index(AuthManager $auth)
{
$user = $auth->user();
}

With the Facade under the hood, it's just one line.

Using Facade

public function index()
{
$user = Auth::user();
}

So, in short, Facade is just like a shortcut to a specific class.

Now that we know what they are let's think about whether we need to use them and how.

First, it's convenient to use the Facades from...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 63 courses (1128 lessons, 42 h 01 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord