Custom Blade Directives
You can create custom Blade directives for domain-specific logic. Define them in a service provider's boot() method using Blade::directive(). This is useful for formatting dates, checking permissions, or any repeated logic in views.
Custom Directives
// In AppServiceProvider boot() method:
use Illuminate\Support\Facades\Blade;
public function boot(): void
{
// @datetime($timestamp) — format a date
Blade::directive('datetime', function (string $expression) {
return "<?php echo ($expression)->format('M d, Y'); ?>";
});
// @role('admin') ... @endrole
Blade::if('role', function (string $role) {
return auth()->check() && auth()->user()->hasRole($role);
});
}
// Usage in Blade:
<p>Published: @datetime($post->created_at)</p>
@role('admin')
<a href="/admin">Admin Panel</a>
@endroleTip
Tip
Practice Custom Blade Directives in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Blade = elegant PHP templating. Auto-escapes output.
Practice Task
Note
Practice Task — (1) Write a working example of Custom Blade Directives from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Custom Blade Directives is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.