Engineering note · Laravel

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.

By Published

Laravel

Step 1: Create a Custom Blade Directive

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

CODE SAMPLE Code snippet
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:

CODE SAMPLE Code snippet
<!-- 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.

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

Then, in your Blade file:

CODE SAMPLE Code snippet
@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!

More engineering notes

Using --ignore-platform-req and --ignore-platform-reqs with Composer

Using --ignore-platform-req and --ignore-platform-reqs flags to bypass specific or all platform requ...

Log Requests with Custom Middleware

Implement custom middleware to log incoming requests, helping in tracking and analyzing application...