How to create facade in laravel

how-to-create-facade-in-laravel

Hello buddy, in this article we will learn about how to create a facade in laravel or you can say a custom facade in laravel.

But before creating a facade, do you know what is facade in laravel ?

In simple language, I must say In a Laravel application, a facade is a class that provides access to an object from the container.

Follow the below steps to create facade in laravel

  1. Create Class File
  2. Create Facade Class
  3. Add it in service provider
  4. Use Facade class

Step:1 Create Class File

Let’s suppose you are integrating a shipping API named Delhivery and for that shipping API, you want to create a facade, Let’s create a class file named Delhivery.php, I have created a folder named as utility and created a file Delhivery.php inside that folder, add the below code into it, please change the namespace as per your code

<?php

namespace Modules\ThirdParty\Utility;

/**
 * Delhivery Class, Contains all api consumption code here
 */
class Delhivery
{

    
    function createOrder()
    {
        return 'hello';
    }
}

Step:2 Create Facade Class

In the step we will create a facade class which will extends facade our facade class name will be DelhiveryAPI,create a folder named as facade and after the create file named as DelhiveryAPI.php in that folder, and add the below code into it.

<?php

namespace Modules\ThirdParty\Facade;

use Illuminate\Support\Facades\Facade;

/**
 * Paytm Helper is used for commonly used function
 */
class DelhiveryAPI extends Facade
{

    protected static function getFacadeAccessor()
    {
        return 'delhivery';
    }
}

Step:3 Add it in service provider

Now we will add our facade in our service provider inside boot function, look for the below code.

/**
     * Boot the application events.
     *
     * @return void
     */
    public function boot()
    {

        $this->app->bind('delhivery',function(){
            return new Delhivery();
        });
    }

Step:4 Use facade class

Now we will call our createOrder() function using facade in the controller, see the below code.

class QshipController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function calculateShipping()
    {   
        
        // dd(DelhiveryAPI::createOrder());
    }
}

The above code will return delhivery.

I hope now understand how we can create a custom facade in laravel, If this article really helps you please rate me 5. Thanks for reading and visiting our blog.

If you still have confusion in creating a custom facade in laravel, put a comment we will try to reply to you as soon as possible.

0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Spread the love
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x