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.
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.
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:
Make a PHP Class File.
Bind the class to Service Provider.
Add the ServiceProvider to Config\app.php as a provider.
Create a class that extends this class to lluminate\Support\Facades\Facade.
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
App
Illuminate\Foundation\Application
app
Artisan
Illuminate\Console\Application
artisan
Auth
Illuminate\Auth\AuthManagen
auth
Auth (Instance)
Illuminate\Auth\Guard
Blade
Illuminate/ViewlCompilers\BladeCompiler
blade.compiler
Cache
Illuminate\Cache\Repository
cache
Config
Illuminate\Config\Repository
config
Cookie
Illuminate\Cookie\CookieJar
cookie
Crypt
Illuminate\Encryption\Encrypter
encrypter
DB
Illuminate\Database\DatabaseManager
db
DB (Instance)
lluminate\Database\Connection
Event
Illuminate\Events\Dispatcher
events
File
Illuminate\Filesystem\Filesystem
files
Form
Illuminate\Html\FormBuilder
form
Hash
Illuminate\Hashing\HasherInterface
hash
HTML
Illuminate\Html\HtmlBuilder
html
Input
Illuminate\Http\Request
request
Lang
Illuminate\Translation\Translator
translator
Log
Illuminate\Log\Writer
log
Mail
Illuminate\Mail\Mailer
mailer
Paginator
Illuminate\Pagination\Factory
paginator
Paginator (Instance)
Illuminate\Pagination\Paginator
Password
Illuminate\Auth\Reminders\PasswordBroke r
auth.reminder
Queue
Illuminate\QueuelQueueManagen
queue
Queue (Instance)
Illuminate\Queue\Queuelnterface
Queue (Base Class)
Illuminate\Queue\Queue
Redirect
Illuminate\Routing\Redirector
redirect
Redis
Illuminate\Redis\Database
redis
Request
Illuminate\Http\Request
request
Response
Illuminate\Support\Facades\Response
Route
Illuminate\Routing\Router
router
Schema
Illuminate\Database\Schema\Blueprint
Session
Illuminate\Session\SessionManager
session
Session (Instance)
Illuminate\Session\Store
SSH
Illuminate\Remote\RemoteManager
remote
SSH (Instance)
lluminate\Remote\Connection
URL
Iluminate\Routing\UrlGenerator
url
Validator
Illuminate/Validation\Factory
validator
Validator (Instance)
Illuminate\Validation\Validator
View
Illuminate\View|Factory
view
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.
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.