$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[December 09, 2025] Laravel

Laravel Blade: Custom Directives

Laravel Blade: Custom Directives

────────────────────────────────────────────────────────

Laravel Blade: Custom Directives

Tip: Register Custom Directive

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

Usage: @datetime($post->created_at).

Gotcha: Blade Caches Compiled Views

After adding a custom directive, run php artisan view:clear to see changes.

Tip: Conditional Directives

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

Usage: @admin ... @endadmin.

Gotcha: Directive Receives Raw String

The $expression parameter is the raw string from the template, not evaluated PHP.

Tip: Block Directives

Blade::directive('section', function ($expression) {
    return '<section class="' . $expression . '">';
});
Blade::directive('endsection', function () {
    return '</section>';
});

Gotcha: Don't Overuse Custom Directives

Prefer view components for complex logic. Directives are best for simple formatting.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

Blade components are deceptively simple. The mistake I see repeatedly is putting too much logic in component classes — a component should render, not compute. I once inherited a codebase where a Sidebar component made three database queries in its constructor. Components are views with a tiny bit of presentation logic, not controllers in disguise. Also, use @aware sparingly; it creates implicit couplings that make refactoring a nightmare.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts