Laravel — P68: Defining Custom Directives in Blade

Dino Cajic
Geek Culture
Published in
2 min readMar 16, 2023

--

Dino Cajic on defining custom directives in Laravel Blade

How many times have you wished that a specific directive existed in Blade? If the answer to that question is “many,” then do I have a surprise for you. You can create your own directives in Blade.

First, you need to create a service provider using the php artisan make:provider command. This provider will register your Blade directives with Laravel.

# php artisan make:provider CustomBladeServiceProvider

INFO Provider [app/Providers/CustomBladeServiceProvider.php] created successfully.

#
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

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

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

Next, you need to register the provider in the config/app.php file.

'providers' => [

/*
* Laravel Framework Service Providers...
*/
// ...
App\Providers\CustomBladeServiceProvider::class,

In your CustomBladeServiceProvider class, you can define your custom Blade directive using the Blade::directive method.

--

--

Dino Cajic
Geek Culture

Author of An Illustrative Introduction to Algorithms. IT Leader with a B.S. in Computer Science, a minor in Biology, and a passion for learning.