Create Custom Facade Class in Laravel 8 Tutorial

Reading Time: 7 minutes
12,361 Views

In a Laravel application, a facade is a class that provides access to an object from the container. The mechanism that makes this work is in the Facade class. Laravel’s facades or any custom facades we create, will extend the base Illuminate\Support\Facades\Facade class.

Laravel provide default facade like Route, Redirect, Cookie, App, Crypt etc.

Inside this article we will see the concept of create custom facade class in laravel 8. This tutorial will be super easy to understand and implement it in your application.

Let’s get started.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

composer create-project --prefer-dist laravel/laravel blog

To start the development server of Laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.


Steps to Create a Custom Facade Class

These are the steps we need to follow step by step to create laravel custom facade.

  • Create a PHP class file
  • Bind that class to Service Provider [ Either we can create our own service provider or via application’s AppServiceProvider ]
  • If created Custom Service Provider – Register that Service Provider in /config/app.php
  • Create a class that extends Illuminate\Support\Facades\Facade
  • Register your facade in /config/app.php in aliases

Let’s proceed with these steps.


Create a PHP Class File

Create a folder with name Support inside /app. Inside this folder we will store php class file and custom facade class.

Next,

Create a PHP file say MyString.php inside /app/Support folder.

Open MyString.php and write this complete code into it.

<?php 

namespace App\Support;
 
class MyString
{
    // This function converts a string into slug format
    public function slugify($text)
    {
        // replace non letter or digits by -
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        // trim
        $text = trim($text, '-');

        // remove duplicate -
        $text = preg_replace('~-+~', '-', $text);

        // lowercase
        $text = strtolower($text);

        if (empty($text)) {
            echo 'n-a';
        }

        echo $text;
    }
}

Inside this PHP class we have created a method which converts a string value into slug format.


Bind PHP Class to Service Provider

We have two options to bind custom php class file.

  • By Using AppServiceProvider.php
  • By Creating Custom Service Provider

We will see both ways.

By Using AppServiceProvider.php

Open AppServiceProvider.php from /app/Providers folder. We need to a block of code into it’s register method.

Open AppServiceProvider.php and work accordingly.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Support\MyString;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('mylibrary',function($app){
            return new MyString;
        });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

No need to do anything for now. That’s it.

By Creating Custom Service Provider

Open project into terminal and type this artisan command to create service provider.

$ php artisan make:provider TestingFacadesServiceProvider

It will creates a file with name TestingFacadesServiceProvider.php inside /app/Providers folder.

Open TestingFacadesServiceProvider.php and write this complete code into it.

<?php

namespace App\Providers;

use App\Support\MyString;
use Illuminate\Support\ServiceProvider;

class TestingFacadesServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('mylibrary',function($app){
            return new MyString;
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Next, we need to register this custom service provider to Application.

Open app.php from /config folder.

Search for providers, Add this line into it.

//...

App\Providers\TestingFacadesServiceProvider::class,

Create a Class That Extends Facade

Create another class that will extend Illuminate\Support\Facades\Facade class and use the method called getFacadeAccessor().

Create a file with name say MyFacade.php inside /app/Support folder.

Open MyFacade.php and write this small complete code into it.

<?php
  
namespace App\Support;
  
use Illuminate\Support\Facades\Facade;
  
class MyFacade extends Facade{

    protected static function getFacadeAccessor() { 

        return 'mylibrary'; 
    }
}

Register Custom Facade Class

Open app.php file from /config folder.

Search for aliases, add this line of code into it.

//...

'MyFacade'=> App\Support\MyFacade::class

Custom Facade Usage in Application

Now, we need to test application. We will use by two ways –

  • By Creating a closure route.
  • In Controllers

By Closure Route

Open web.php file from /routes folder. Add this route into it.

Route::get('custom-slug', function() {

    $text = "Custom Facade in Laravel 8";

    MyFacade::slugify($text);

});

Output will be

URL – http://127.0.0.1:8000/custom-slug

custom-facade-in-laravel-8

Using in Controllers

Let’s create a controller. Run this artisan command to terminal.

$ php artisan make:controller DataController

It will create a file DataController.php file at /app/Http/Controllers folder.

Open DataController.php file and write this complete code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use MyFacade;

class DataController extends Controller
{
    public function getSlug(){

        $text = "Custom Facade in Laravel 8";

        MyFacade::slugify($text);
    }
}

Open web.php file and add this route into it.

# Add this to header
use App\Http\Controllers\DataController;

//...

Route::get("custom-slug", [DataController::class, "getSlug"]);

Output will be

URL – http://127.0.0.1:8000/custom-slug

custom-facade-in-laravel-8

We hope this article helped you to learn about Create Custom Facade Class in Laravel 8 Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more