Laravel Blade Directives
19 May 2025 | Category: Laravel
Blade, Laravel’s templating engine, provides a rich set of directives that simplify common tasks in view templates, making them more expressive and secure. Among these, @csrf
and @method
are critical for handling forms, while other directives like @error
, @auth
, and @guest
streamline validation, authentication, and conditional rendering. This SEO-friendly, plagiarism-free guide explains key Blade directives, focusing on @csrf
, @method
, and other commonly used ones, with practical examples and best practices. Based on Laravel 11 (as of May 19, 2025), this tutorial is designed for beginners and intermediate developers.
What are Blade Directives?
Blade directives are special syntax constructs (starting with @
) that provide shortcuts for common PHP operations in templates. They enhance readability, reduce boilerplate code, and integrate seamlessly with Laravel’s features, such as form handling, authentication, and error management.
Key Benefits
- Simplicity: Replace complex PHP logic with concise syntax.
- Security: Built-in protections like CSRF tokens and escaped output.
- Maintainability: Keep templates clean and focused on presentation.
- Integration: Work naturally with Laravel’s ecosystem (e.g., routing, validation).
This guide focuses on form-related directives (@csrf
, @method
), error handling (@error
), authentication (@auth
, @guest
), and other useful directives, with examples of their usage.
Form-Related Directives
Forms are a critical part of web applications, and Blade provides directives to make form handling secure and straightforward, especially for web
routes (defined in routes/web.php
).
1. @csrf
The @csrf
directive generates a hidden CSRF (Cross-Site Request Forgery) token field required for POST, PUT, PATCH, and DELETE requests in web
routes. CSRF protection prevents unauthorized requests by verifying that the request originates from your application.
Syntax:
@csrf
Example (Creating a Post):
<form method="POST" action="{{ route('posts.store') }}">
@csrf
<input type="text" name="title" value="{{ old('title') }}">
<textarea name="content">{{ old('content') }}</textarea>
<button type="submit">Create Post</button>
</form>
- Output:
<input type="hidden" name="_token" value="generated-csrf-token">
- Purpose: Adds a hidden
_token
field to validate the request. - When Required: Mandatory for non-GET forms in
web
routes (not needed forapi
routes, which are stateless).
Controller Example:
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
]);
Post::create($validated);
return redirect()->route('posts.index');
}
2. @method
The @method
directive spoofs HTTP methods (e.g., PUT, PATCH, DELETE) for forms, as HTML forms only support GET and POST. This is essential for RESTful resource controllers handling updates or deletions.
Syntax:
@method('HTTP_METHOD')
Example (Updating a Post):
<form method="POST" action="{{ route('posts.update', $post) }}">
@csrf
@method('PUT')
<input type="text" name="title" value="{{ old('title', $post->title) }}">
<textarea name="content">{{ old('content', $post->content) }}</textarea>
<button type="submit">Update Post</button>
</form>
- Output:
<input type="hidden" name="_method" value="PUT">
- Purpose: Tells Laravel to treat the POST request as a PUT request.
- When Required: Needed for PUT, PATCH, or DELETE actions in
web
routes.
Controller Example:
public function update(Request $request, Post $post)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
]);
$post->update($validated);
return redirect()->route('posts.index');
}
Error Handling Directive
3. @error
The @error
directive displays validation errors for a specific form field, simplifying error handling after form submission failures.
Syntax:
@error('field')
<!-- Error message -->
@enderror
Example:
<form method="POST" action="{{ route('posts.store') }}">
@csrf
<div>
<label for="title">Title</label>
<input type="text" name="title" id="title" value="{{ old('title') }}">
@error('title')
<span class="error">{{ $message }}</span>
@enderror
</div>
<div>
<label for="content">Content</label>
<textarea name="content" id="content">{{ old('content') }}</textarea>
@error('content')
<span class="error">{{ $message }}</span>
@enderror
</div>
<button type="submit">Create Post</button>
</form>
- $message: The validation error message for the field.
- old(‘title’): Repopulates the field with the previous input after validation failure.
- Purpose: Displays field-specific errors returned by Laravel’s validator.
Controller Example:
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'content' => 'required|string',
]);
Post::create($validated);
return redirect()->route('posts.index');
}
- If validation fails, Laravel redirects back with errors stored in the session.
Alternative: Display all errors:
@if ($errors->any())
<ul class="errors">
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
Authentication Directives
Blade provides directives to conditionally render content based on the user’s authentication status.
4. @auth
The @auth
directive renders content if the user is authenticated (logged in).
Syntax:
@auth
<!-- Content for authenticated users -->
@endauth
Example:
@auth
<p>Welcome, {{ auth()->user()->name }}!</p>
<a href="{{ route('logout') }}">Logout</a>
@endauth
- Purpose: Displays content only for logged-in users.
- Optional Guard: Specify a guard for multi-authentication setups:
@auth('admin')
<p>Welcome, Admin!</p>
@endauth
5. @guest
The @guest
directive renders content if the user is not authenticated (guest).
Syntax:
@guest
<!-- Content for guests -->
@endguest
Example:
@guest
<p>Please <a href="{{ route('login') }}">log in</a> to continue.</p>
@endguest
- Purpose: Displays content for unauthenticated users.
- Optional Guard:
@guest('admin')
<p>Please log in as an admin.</p>
@endguest
Combined Example:
@auth
<p>Welcome, {{ auth()->user()->name }}!</p>
@else
<p>Please <a href="{{ route('login') }}">log in</a>.</p>
@endauth
Other Useful Directives
Blade offers additional directives for common tasks, enhancing template functionality.
6. @isset
Checks if a variable is defined and not null.
Syntax:
@isset($variable)
<!-- Content -->
@endisset
Example:
@isset($posts)
<p>{{ count($posts) }} posts found.</p>
@endisset
7. @empty
Checks if a variable is empty (e.g., empty array, null, empty string).
Syntax:
[TRUNCATED]