How to create custom Blade Directives in Laravel
In this guide, we will walk through how to create and use custom Blade directives to make your Laravel views cleaner, more maintainable, and reusable.
Laravel

Blade is Laravel's powerful templating engine, providing clean and simple syntax for managing views. However, when working with Blade templates, you might find yourself repeating certain logic multiple times. This is where custom Blade directives come in handy.

In this guide, we'll walk through how to create and use custom Blade directives to make your Laravel views cleaner, more maintainable, and reusable. We'll start with the basics and progressively move towards more advanced implementations.

Prerequisites

Before diving in, ensure you have the following:

  • A Laravel project (Laravel 10+ recommended)
  • Composer installed
  • Basic knowledge of Laravel Blade templates

Setting Up a Laravel Project

If you don't have a Laravel project set up, create a new one using:

composer create-project laravel/laravel blade-directives-example
cd blade-directives-example
php artisan serve
 

Understanding Blade Directives

Blade comes with built-in directives such as @if, @foreach, and @auth. However, Laravel allows us to define our own custom Blade directives to reduce redundancy and improve code readability.

Problem: Repeating Authentication Checks

Consider a scenario where you frequently check if a user is an admin:

@if(auth()->user() && auth()->user()->isAdmin())
    <p>Welcome, Admin!</p>
@endif

If this logic appears multiple times in your Blade files, it makes the code harder to maintain.

Creating a Custom Blade Directive

To solve this, we can define a custom Blade directive. Open app/Providers/AppServiceProvider.php and modify the boot method:

use Illuminate\Support\Facades\Blade;

public function boot()
{
    Blade::directive('isAdmin', function () {
        return "<?php if(auth()->user() && auth()->user()->isAdmin()): ?>";
    });
    Blade::directive('endIsAdmin', function () {
        return "<?php endif; ?>";
    });
}

Using the Custom Directive in Blade Templates

Now, instead of writing the conditional logic repeatedly, use the new @isAdmin directive:

@isAdmin
    <p>Welcome, Admin!</p>
@endIsAdmin

This makes the Blade template more readable and maintainable.

Advanced Custom Blade Directives

1. Formatting Dates

If you frequently format dates in your Blade templates, create a directive for it:

Blade::directive('formatDate', function ($expression) {
    return "<?php echo ($expression)->format('M d, Y'); ?>";
});

Usage:

<p>Published on: @formatDate($post->created_at)</p>

2. Checking User Roles

If your application has multiple roles, create a more dynamic directive:

Blade::directive('role', function ($role) {
    return "<?php if(auth()->check() && auth()->user()->role === $role): ?>";
});
Blade::directive('endRole', function () {
    return "<?php endif; ?>";
});
 

Usage:

 

@role('editor')
    <p>You have editing privileges.</p>
@endRole

 

3. Creating Shortened Conditional Directives

For boolean checks, create shorthand directives:

 

Blade::directive('checked', function ($condition) {
    return "<?php echo $condition ? 'checked' : ''; ?>";
});

Usage:

<input type="checkbox" @checked($user->isActive)>
 

Building a Laravel Project with Custom Blade Directives

To solidify our understanding, let's build a small Laravel project that utilizes custom Blade directives.

Step 1: Create a New Laravel Project

If you haven't already, set up a new Laravel project:

 

composer create-project laravel/laravel blade-example
cd blade-example

 

Step 2: Configure Authentication

For this project, install Laravel Breeze for authentication:

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate

Step 3: Implement Custom Blade Directives

Modify app/Providers/AppServiceProvider.php to include:

use Illuminate\Support\Facades\Blade;

public function boot()
{
    Blade::directive('isAdmin', function () {
        return "<?php if(auth()->user() && auth()->user()->isAdmin()): ?>";
    });
    Blade::directive('endIsAdmin', function () {
        return "<?php endif; ?>";
    });
}

Step 4: Use Custom Directives in Views

Edit resources/views/dashboard.blade.php and add:

@extends('layouts.app')

@section('content')
    <h1>Dashboard</h1>
    @isAdmin
        <p>Welcome, Admin! You have full access.</p>
    @endIsAdmin
@endsection

Step 5: Test the Application

Run the application and log in with an admin account:

php artisan serve

Navigate to /dashboard and check if the custom directive works.

Best Practices for Blade Directives

  • Keep logic minimal: Blade directives should focus on rendering output, not performing complex operations.
  • Use clear and meaningful names: The directive name should clearly indicate its purpose.
  • Avoid excessive use: Don't overuse custom directives; Laravel's built-in directives often suffice.

Conclusion

Custom Blade directives are a powerful way to simplify your Laravel views, improve readability, and reduce redundancy. By defining your own directives, you can make your Blade templates more expressive and maintainable.

Try implementing custom directives in your next Laravel project and let me know how they improve your development workflow!

Author: moses on 15-02-2025
Related Posts
Built by codecontent.pro in partnership with Laraveldev.pro
© 2025 Laraveldev.pro