25th Feb 2022

Laravel: Facades

Web

Written By, Rinkal Jasani

What is Facades

Facades:

  • Laravel Facade is a pattern that is used in the Service Locator Pattern. The facade is one wrapper of non-static function in laravel, so facades are wrapped non-static function into a static function. In simple terms it was to provide a static interface to your non static method or function.

laravel_facades

Source

Benefits of facades

  • They provide a short, memorable syntax that allows you to use Laravel’s features without remembering long class names. so we can create a clean and effective way of accessing objects.
  • Facades provide simplicity to your code. For example: If you want to create packages for your application you can easily create by using facades.
  • Also, we can create our own facades and we can use them as a package of your application.

Built-in laravel facades

In laravel so many built in laravel facades that provide some built-in functionality to our application just import those facades in your file and use them through your page.

Ex:

Facade Class Reference

How to create custom facades

Step 1 : We create a folder App\Test then we create a PHP helper class Test in the folder. In this class you can create multiple methods and then use in future as like laravel controller methods

Step 2 : We create a service provider and bind it. Use the below command to generate provide in our project.
Now we add below code to register a method to bind the service provider. Here we just bind our class with our service provider ( Not class method )

laravel_facades_step2

Step 3 : Now we have to register the service provider and add below code to register it in config/app.php as providers.

laravel_facades_step3

Step 4 : Now we create a class TestFacade in App\Test which will extend Facades. Illuminate\Support\Facades\Facade and add below code to this class.

Step 5 : Now we register the class TestFacade in config/app.php as aliases

laravel_facades_step5

Step 6 : Now we can try to use facades like name of facades alias that point to register facades class method.

laravel_facades_step6

Step 7: Execute particular route in your browser

laravel_facades_step7

Conclusion

Now we know that the Laravel facade makes it super easy to call methods, and injecting the actual dependencies could really pay off down the line. Of course Laravel Facade has its own advantages and disadvantages. It depends on the developer to select the right option.

Written By,

Web Developer at Yudiz Solutions Pvt. Ltd