How to create custom facade in laravel 5.2?

By Hardik Savani November 5, 2023 Category : Laravel

Sometimes we are use repeat code and repeatedly use function at that time we can create custom facade for our project, that way you can create functions and use it.So, How to generate custom facade, I give you the few step to create custom facade:

Step 1:Create class file app/ItSolution/DemoClass.php

In Following step, first you should create "ItSolution" directory in app folder and create file DemoClass.php(app/ItSolution/DemoClass.php).now copy the following code in your DemoClass.php file.

app/ItSolution/DemoClass.php

namespace App\ItSolution;

class DemoClass {

public function productImagePath($image_name)

{

return public_path('images/products/'.$image_name);

}

public function changeDateFormate($date,$date_format){

return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)

->format($date_format);

}

}

Step 2:Create ServiceProvider

In this step you should create service provider for bind class, so fire your terminal or cmd this following command:

php artisan make:provider 'DemoClassServiceProvider'

Ok, now you can find new file DemoClassServiceProvider.php in your providers(app/Providers) directory.So, Basically open app/Providers/DemoClassServiceProvider.php and copy the following code:

app/Providers/DemoClassServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App;

class DemoClassServiceProvider extends ServiceProvider

{

/**

* Bootstrap the application services.

*

* @return void

*/

public function boot()

{

//

}

/**

* Register the application services.

*

* @return void

*/

public function register()

{

App::bind('democlass', function()

{

return new \App\ItSolution\DemoClass;

});

}

}

Step 3:Create Facade Class

In this step create another class app/ItSolution/DemoClassFacade.php, In this class you have to extend "Illuminate\Support\Facades\Facade" class, copy following link:

namespace App\ItSolution;

use Illuminate\Support\Facades\Facade;

class DemoClassFacade extends Facade{

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

}

Step 4:Register Service Provider

Simple Register your service provider in Config\app.php like this way :

// In providers array

App\Providers\DemoClassServiceProvider::class,

And also add aliase for facade in this file like this way :

// In aliases array

'DemoClass'=> App\ItSolution\DemoClassFacade::class

Step 5:composer dump

This is the last step and you have to do just composer dump-autoload in your terminal:

composer dump-autoload

At Last you can use this way:

Route::get('democlass', function(){

$imagepath = DemoClass::productImagePath('image.jpg');

print_r($imagepath);

});

Tags :
Shares