Custom Blade Directives: The Secret Weapon for Clean Views

· 2 min read

While Blade Components are a great UI solution, sometimes you need small commands (Directives) similar to @if or @foreach rather than wrapping the entire HTML component.

1. The Nature of Blade Directives

Blade reads the .blade.php file structure and compiles it into pure PHP, which is then cached in storage/framework/views. Therefore, the goal of a Directive is to return the corresponding PHP logic string.

2. Registering a Blade Directive

Register Directives in the boot method of App\Providers\AppServiceProvider.

Example 1: Handling Currency Format (@money)

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Blade::directive('money', function ($expression) {
            return "<?php echo number_format($expression, 2) . ' USD'; ?>";
        });
    }
}

Usage in Blade:

<div class="price">
    Product Price: @money($product->price)
</div>

When rendered, it becomes:

<?php echo number_format($product->price, 2) . ' USD'; ?>

Example 2: Simplifying Authorization Checks (@role)

Create custom directives for the application's authorization logic (when not using external packages).

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

Blade::directive('endrole', function () {
    return "<?php endif; ?>";
});

Usage:

@role('admin')
    <a href="/admin/dashboard">Access Admin Panel</a>
@endrole

3. Custom If Statements (Blade::if)

Sometimes concatenating PHP strings as above can be tedious for boolean-returning conditional logic. Blade::if is a much cleaner solution:

Blade::if('env', function ($environment) {
    return app()->environment($environment);
});

Usage:

@env('local')
    <!-- Only show debug logic in Local environment -->
    <script src="http://localhost:35729/livereload.js"></script>
@endenv

By creating Custom Directives, frontend developers do not need to write PHP code to handle data formatting logic, and the views can focus 100% on HTML rendering.

Comments