SyntaxStudy
Sign Up
Laravel Blade Directives and Service Injection
Laravel Beginner 1 min read

Blade Directives and Service Injection

Blade ships with directives for authorization (@can, @cannot, @canany), authentication (@auth, @guest), environment checking (@env, @production), and CSRF protection (@csrf). The @method directive generates a hidden input for HTML form method spoofing, required for PUT, PATCH, and DELETE forms since HTML only supports GET and POST natively. Custom Blade directives are registered in a service provider using Blade::directive(). They accept a string expression and return PHP code as a string. For more complex logic, Blade::if() creates custom conditional directives that accept a closure. These are perfect for encapsulating permission checks or environment conditions that would otherwise clutter templates. The @inject directive pulls a service out of the service container directly into a template, enabling access to services without passing them from the controller. The @each directive renders a partial view for each item in a collection. Stacks — pushed to with @push and rendered with @stack — allow child views to inject CSS or JavaScript into specific points of a parent layout, useful for per-page scripts.
Example
{{-- Authorization directives --}}
@can('update', $post)
    <a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan

@canany(['update', 'delete'], $post)
    <div class="action-buttons">...</div>
@endcanany

{{-- Authentication directives --}}
@auth
    <span>Hello, {{ auth()->user()->name }}</span>
@else
    <a href="{{ route('login') }}">Log in</a>
@endauth

{{-- CSRF and method spoofing --}}
<form action="{{ route('posts.update', $post) }}" method="POST">
    @csrf
    @method('PUT')
    <input type="text" name="title" value="{{ old('title', $post->title) }}">
    <button type="submit">Update</button>
</form>

{{-- Service injection --}}
@inject('metrics', 'App\Services\MetricsService')
<p>Total posts: {{ $metrics->totalPosts() }}</p>

{{-- Registering a custom directive in AppServiceProvider::boot() --}}
{{-- \Blade::directive('money', fn($e) => "<?php echo number_format($e, 2); ?>"); --}}
{{-- Usage: @money($post->price) --}}