'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Sep 12, 2023
Easy

Laravel Facades

Author Sanjana Yadav
0 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

A developer knows how important a framework is. We want a framework to ease the basic tasks required in the majority of web projects, including authentication, routing, sessions, and caching, to take the misery out of development. We are learning one such framework called Laravel. 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.

Today, we will understand the facades class in Laravel.

Laravel Facades

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

When To Use Facades

Usage example

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');

Creating 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 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

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

What are facades in Laravel?

A facade is a class in a Laravel application that allows access to an object from the container. This task is done by machinery in the Facade class.

What is a facade PHP?

Facade is a structural design pattern that creates simple (but constrained) interfaces to a complicated set of classes, libraries, or frameworks. While Facade reduces the overall complexity of the program, it also aids in the consolidation of unneeded dependencies.

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.

What is the use of facade?

Facades in Laravel simplify code by providing a straightforward way to access complex features. They act as shortcuts, making it easier to use Laravel's capabilities without understanding intricate details.

Conclusion

In this article, we learned about the Facades class in Lavarel in detail. We learned to create a custom facade, and we also saw different types of facades and underlying classes.

We hope this blog has helped you understand Laravel Facades and how they function. You may read more about Laravel interview questionsInterview Questions for Design Pattern and much more.

Make sure you enroll in the courses we provide, take mock tests, solve problems, and interview puzzles. Also, you can prepare for interviews with interview experiences and interview bundle.

Keep learning and keep growing, Ninjas!

Previous article
Laravel Eloquent
Next article
How to Get Internships In College?
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass