Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are facades in Laravel?
3.
When To Use Laravel Facades?
4.
How to Create Laravel Facades?
5.
How Facades in Laravel Work?
6.
Facade Class Reference
7.
Example of Laravel Facades
8.
Frequently Asked Questions
8.1.
Where is Facades folder in Laravel?
8.2.
What is the difference between helper and facade in Laravel?
8.3.
Why are facades used?
8.4.
How to create new Facade in Laravel?
9.
Conclusion
Last Updated: Sep 20, 2024
Easy

Laravel Facades

Author Sanjana Yadav
0 upvote

Introduction

Laravel Facades are like shortcuts in Laravel. They let you access complex functionality with simple, easy-to-remember names. They're like a friendly face for powerful features in your Laravel applications.

Laravel Facades

What are facades in Laravel?

Facades in Laravel act like simplified interfaces to the various features available in the application. Laravel comes with a bunch of facades that let you access different parts of the system.

Think of facades as middlemen that make it easy to use Laravel's features with simple and clear code. They are like shortcuts to the real functionality hidden behind the scenes. Using facades, you can write code that's easy to understand and test, even if you don't know all the technical details of how facades work.

Also read about - Laravel Eloquent

When To Use Laravel Facades?

In the following example, a call is made to the Laravel Log class. Looking at this code, one could think that the static method get on the Log class is being called.

$value = Log::get('key');


But, if we examine the Illuminate\Support\Facades\Log class, we can find that there is no static method get:

class Log extends Facade {
  @return string
   protected static function getFacadeAccessor() { return 'Log'; }
}


Here, the class log extends the base Facade class and provides a method called getFacadeAccessor(). We need to remember that the purpose of this function is to return the name of an IoC binding.

When a user calls a static method on the log facade, Laravel resolves the log binding from the IoC container and executes the requested method (in this example, get) on that object.

So, our Log::get can also be written as:

$value = $app->make('log')->get('key');

How to Create Laravel Facades?

It is simple to create a façade for our own application or package. We simply need three items:

  • An IoC binding.
  • A facade class.
  • An alias setup for a facade.


Below are the steps to understand this:

  1. Make a PHP Class File.
  2. Bind the class to Service Provider.
  3. Add the ServiceProvider to Config\app.php as a provider.
  4. Create a class that extends this class to lluminate\Support\Facades\Facade.
  5. Add aliases to point 4 in Config\app.php.

Let us understand these steps through an example:

Consider the following example. We have a StudentRolls\Students class defined here.

namespace StudentRolls;
class Student {
    public function work() 
    {
        //
    }
}


This class might be in our app/models directory or any other location that Composer is aware of.

This class must be able to be resolved from the IoC container. So, let's include a binding:

App::bind('students', function()
{
    return new \StudentRolls\Student;
});


This binding may be registered by adding it to the register function of a new service provider named StudentMarksProvider. Then, in the app/config/app.php configuration file, you may instruct Laravel to load your service provider.

use Illuminate\Support\Facades\Facade;

Following that, we can write our own facade class:

class Student extends Facade {
 
    protected static function getFacadeAccessor() { return 'student'; }
}


Finally, in the app/config/app.php configuration file, we can add an alias for our facade to the aliases array. We can now invoke the work function on a Student class object.

Student::work();

How Facades in Laravel Work?

Facades work like friendly gatekeepers for complex systems. They provide a simplified and user-friendly interface, hiding the intricate details behind them. Think of a building with a beautiful entrance; you don't need to know the structure's complexity. Similarly, facades simplify interactions with software or machines. They bundle multiple operations into one easy-to-use function, shielding users from complexities. 

For example, when you start your computer, you click an icon, but behind the scenes, many tasks happen. Facades make it as simple as clicking that icon, making complicated things accessible to everyone.

Facade Class Reference

Facade

Class

loC Binding

AppIlluminate\Foundation\Applicationapp
ArtisanIlluminate\Console\Applicationartisan
AuthIlluminate\Auth\AuthManagenauth
Auth (Instance)Illuminate\Auth\Guard 
BladeIlluminate/ViewlCompilers\BladeCompilerblade.compiler
CacheIlluminate\Cache\Repositorycache
ConfigIlluminate\Config\Repositoryconfig
CookieIlluminate\Cookie\CookieJarcookie
CryptIlluminate\Encryption\Encrypterencrypter
DBIlluminate\Database\DatabaseManagerdb
DB (Instance)lluminate\Database\Connection 
EventIlluminate\Events\Dispatcherevents
FileIlluminate\Filesystem\Filesystemfiles
FormIlluminate\Html\FormBuilderform
HashIlluminate\Hashing\HasherInterfacehash
HTMLIlluminate\Html\HtmlBuilderhtml
InputIlluminate\Http\Requestrequest
LangIlluminate\Translation\Translatortranslator
LogIlluminate\Log\Writerlog
MailIlluminate\Mail\Mailermailer
PaginatorIlluminate\Pagination\Factorypaginator
Paginator (Instance)Illuminate\Pagination\Paginator 
PasswordIlluminate\Auth\Reminders\PasswordBroke rauth.reminder
QueueIlluminate\QueuelQueueManagenqueue
Queue (Instance)Illuminate\Queue\Queuelnterface 
Queue (Base Class)Illuminate\Queue\Queue 
RedirectIlluminate\Routing\Redirectorredirect
RedisIlluminate\Redis\Databaseredis
RequestIlluminate\Http\Requestrequest
ResponseIlluminate\Support\Facades\Response 
RouteIlluminate\Routing\Routerrouter
SchemaIlluminate\Database\Schema\Blueprint 
SessionIlluminate\Session\SessionManagersession
Session (Instance)Illuminate\Session\Store 
SSHIlluminate\Remote\RemoteManagerremote
SSH (Instance)lluminate\Remote\Connection 
URLIluminate\Routing\UrlGeneratorurl
ValidatorIlluminate/Validation\Factoryvalidator
Validator (Instance)Illuminate\Validation\Validator 
ViewIlluminate\View|Factoryview
View (Instance)Illuminate\ViewlView 

Each facade and its underlying class are listed in the above table. This is a handy tool for fast exploring the API documentation for a certain facade root. The IoC binding key is also given wherever needed.

Must Read CakePHP vs Laravel

Example of Laravel Facades

Database Interaction (DB Facade):

use Illuminate\Support\Facades\DB;

$users = DB::table('users')->where('status', 'active')->get();

Sending Emails (Mail Facade):

use Illuminate\Support\Facades\Mail;

Mail::to('aditya@coodingninjas.com')->send(new MyEmail());

File Handling (Storage Facade):

use Illuminate\Support\Facades\Storage;

$contents = Storage::get('aditya.txt');

Authentication (Auth Facade):

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // User is logged in
}

Frequently Asked Questions

Where is Facades folder in Laravel?

The Facades folder in Laravel is located under the vendor/laravel/framework/src/Illuminate/Support/Facades directory.

What is the difference between helper and facade in Laravel?

In Laravel, a helper is a simple, global function for common tasks, while a facade is a structured way to access Laravel services and classes, offering more features and flexibility.

Why are facades used?

Facades in Laravel provide a static interface to classes available in the application's service container, simplifying the usage of complex underlying classes through a readable, memorable syntax.

How to create new Facade in Laravel?

To create a new Facade in Laravel, extend the Illuminate\Support\Facades\Facade class, define an accessor method in your service provider, bind the facade to the service container, and specify the alias in the aliases array within config/app.php.

Conclusion

In this article, we discussed Laravel Facades, which provide a static interface to classes in the service container. Facades simplify the use of complex classes by offering a clean, concise syntax. They enhance readability and make the code more expressive. However, it's important to use Facades judiciously and understand the underlying classes to maintain a clear understanding of the application's architecture.

Recommended Reads

Live masterclass