How To Create Custom Blade Directive in Laravel 10 Tutorial

Reading Time: 5 minutes
476 Views

Blade, Laravel’s powerful templating engine, includes a number of built-in directives to help you simplify your view layer and enhance code reusability. However, there may be times when you need to extend the functionality of Blade by writing your own custom directives. This is where Laravel 10’s full flexibility and customisation shine.

In this detailed article, we will walk you through the process of developing custom Blade directives in Laravel 10. You can encapsulate complex functionality, reuse code snippets, and create a more expressive and compact syntax within your views by designing your own directives.

Read More: How To Create Custom Helper Function in Laravel 10 Tutorial

Laravel Blade is a templating engine that compiles its special syntax back into PHP and HTML. Its special syntax includes directives. Directives are sugar-added functions hiding complex or ugly code behind them.

Few laravel directives are @if, @foreach, @csrf ,etc

With this article you will be able to create your own directives for blade template engine as @customName.

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.

Register Custom Directive

Open AppServiceProvider.php from /app/Providers folder.

To create custom blade directives we will use Blade facade.

Step #1: Import Facade

Add this to header

use Illuminate\Support\Facades\Blade;

Step #2: Register Directive

Create custom directive inside boot() method.

Blade::directive('directiveName', callbackFunction);

Read More: How To Create Custom Log File in Laravel 10 Tutorial

Here, we have the complete code for AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Directive to find cube area
        // Formula Surface area = 6 * side * side
        Blade::directive('cubearea', function ($side) {
            return "<?php echo 6*$side*$side; ?>";
        });

        // Directive to find cube volume
        // Formula V = side * side * side
        Blade::directive('cubevolume', function ($side) {
            return "<?php echo $side*$side*$side; ?>";
        });
    }
}

Here,

We have created two custom blade directives as @cubearea and @cubevolume

@cubearea calculates surface area of cube whereas @cubevolume calculates volume of a cube.

Usage of Custom Blade Directive

Let’s see how to use custom directives inside blade files.

Create cube-maths.blade.php file inside /resources/views folder. Write this complete code into it.

<h2>Cube Surface Area</h2>
@cubearea($side)

<h2>Cube Volume</h2>
@cubevolume($side)

Read More: How To Create Custom Route File in Laravel 10 Tutorial

Add Route

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

//...

Route::get('cube', function () {
  
    $side = 10;
    
    return view("cube-maths", [
        "side" => $side
    ]);
});

//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL – http://127.0.0.1:8000/cube

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

Read More: How To Create Custom Artisan Command in Laravel 10

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.

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