With Redirect and Session Flash Data (Most Common)
With Redirect and Query String
With Laravel Validation Errors
With Custom Named Session Keys
With Toastr or JavaScript Alerts (for AJAX or SPA)
With Laravel Components (Reusable)
In Laravel, rendering error messages can be done in several ways, each with its own use case and benefits. Here are the most common and effective approaches:
With Redirect and Session Flash Data (Most Common)
Controller:
return redirect()->route('login')->with('error', 'Email does not exist');
Blade:
@if(session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
Pros: Works well with redirects; message disappears after one request.
Cons: Only available for the next request (flash data).
With Redirect and Query String
Controller:
return redirect()->route('login', ['loginerror' => 'Email does not exist']);
Blade:
@if(request('loginerror'))
<div class="alert alert-danger">
{{ request('loginerror') }}
</div>
@endif
Pros: Message persists in the URL until removed.
Cons: Message is visible in the URL (not suitable for sensitive info).
With Laravel Validation Errors
Controller:
return redirect()->back()->withErrors(['email' => 'Email does not exist']);
Blade:
@if($errors->has('email'))
<div class="alert alert-danger">
{{ $errors->first('email') }}
</div>
@endif
Pros: Integrates with Laravel's validation system, supports multiple errors.
Cons: Requires using $errors bag, best for form validation.
With Custom Named Session Keys
Controller:
return redirect()->route('login')->with('custom_error', 'Custom error message');
Blade:
@if(session('custom_error'))
<div class="alert alert-warning">
{{ session('custom_error') }}
</div>
@endif
Pros: Useful for multiple types of messages on the same page.
With Toastr or JavaScript Alerts (for AJAX or SPA)
Controller:
return response()->json(['error' => 'Email does not exist'], 422);
Blade/JS:
if(response.error) {
toastr.error(response.error); // Or use alert(response.error)
}
Pros: Great for AJAX, no page reload needed.
Cons: Requires JS and a notification library.
With Laravel Components (Reusable)
Blade Component (resources/views/components/alert.blade.php):
@if($message)
<div class="alert alert-{{ $type ?? 'danger' }}">
{{ $message }}
</div>
@endif
Usage:
<x-alert :message="session('error')" type="danger"/>
Pros: DRY, reusable, customizable.
- With Old Input (for Form Re-population) Controller:
return redirect()->back()->withInput()->with('error', 'Email does not exist');
Blade
:
<input type="email" name="email" value="{{ old('email') }}">
@if(session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
@endif
Top comments (0)