Create Custom Facade Class in Laravel 8 Tutorial

Share this Article
Reading Time: 7 minutes
535 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.

x
Create Custom Facade Class in Laravel 8 Tutorial video

Let’s get started.


Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Learn Composer Installation Steps. Here is the complete command to create a laravel project-

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

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel already installed at 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.

Find More on Laravel 8 Articles here

Leave a Comment