How To Create Custom Facade in Laravel 10 Tutorial

Reading Time: 8 minutes
689 Views

Inside this article we will see the concept i.e How To Create Custom Facade in Laravel 10 Tutorial. Article contains the classified information i.e What is Facade & How to create it in Laravel 10 application.

In Laravel, a Facade is a design pattern that provides a simple and static interface to a complex system, allowing developers to access its features in an easy and intuitive way.

Facades are a key part of Laravel’s service container and are used to abstract complex functionality behind a simple interface.

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.

Read More: How To Use Trait in Laravel 10 Example Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

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

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.

Read More: How To Work with Route Middleware in Laravel 10 Tutorial

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.

The second alternative way by creating own service provider.

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,

Read More: How To Work with Group Middleware in Laravel 10 Tutorial

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'; 
    }
}

Custom Facade Usage

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.

//...

use App\Support\MyFacade;

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

    $text = "Custom Facade in Laravel 10";

    MyFacade::slugify($text);

});

Testing

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

Output will be

custom-facade-in-laravel-10

Using in Controllers

Let’s create a controller. Run this artisan command to project 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 App\Support\MyFacade;

class DataController extends Controller
{
    public function getSlug(){

        $text = "Custom Facade in Laravel 10";

        MyFacade::slugify($text);
    }
}

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

//...
use App\Http\Controllers\DataController;

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

Testing

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

Output will be

custom-facade-in-laravel-10

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

Read More: How To Work with Global Middleware in Laravel 10 Tutorial

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.