Custom Blade Directives in Laravel

Laravel allows you to create custom Blade directives, making it easier to reuse and organize common code in your views.


Step 1: Create a Custom Blade Directive

Add custom directives in the boot method of a service provider, such as AppServiceProvider.

use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // add blade directive like this
        Blade::directive('greet', function ($name) {
            return "<?php echo 'Hello, ' . ucfirst($name) . '!'; ?>";
        });
    }
}

Here, @greet('world') will output "Hello, world!" in your view.

Step 2: Use the Custom Directive in Your Blade File

In any Blade file, use the @greet directive:

<!-- welcome.blade.php -->
@php
    $userName = 'john';
@endphp

<p>@greet($userName)</p>

This will render:

<p>Hello, John!</p>

Another Example: Custom Auth Check Directive

Add a custom directive to check if the user is an admin.

Blade::if('admin', function () {
    return auth()->check() && auth()->user()->is_admin;
});

Then, in your Blade file:

@admin
    <p>Welcome, Admin!</p>
@endadmin

This will show the message only if the logged-in user is an admin.

Custom Blade directives make repetitive tasks easier to handle, allowing to create cleaner and more maintainable views.

Use them to simplify your templates!

You Might Also Like

Implicit and Explicit Route Model Binding

## 1. Implicit Route Model Binding ``` // Define a route with implicit model binding Route::get('us...

Autoload Composer Dependencies for Faster Performance

This command generates an optimized file that maps all the class names to their corresponding file l...