The 419 error in Laravel typically occurs due to an expired CSRF token. Laravel automatically returns this error when it detects an invalid or missing CSRF token during form submissions or AJAX requests. However, you can customize how the application responds to this error and even provide a more user-friendly message.
In this blog post, we’ll cover three different ways you can handle the 419 error in Laravel:
- Show a Different Page for 419 Errors
- Redirect Back with a Custom Message
- Return a JSON Response with a 419 Status Code
1. Show a Different Page for 419 Errors
By default, Laravel renders a generic error page when a 419 error occurs. You can customize this page to provide a more meaningful response to users.
Create a custom error view:
Laravel looks for a specific error view file in the resources/views/errors
directory. Create a file named 419.blade.php
in that folder.
touch resources/views/errors/419.blade.php
Edit the 419.blade.php
file:
Customize this file to display a message informing the user about the expired session or CSRF token issue.
<!-- resources/views/errors/419.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Expired</title>
</head>
<body>
<h1>Session Expired</h1>
<p>Your session has expired. Please refresh the page and try again.</p>
<a href="{{ url('/') }}">Go to Homepage</a>
</body>
</html>
Test:
Now, when a 419 error occurs, Laravel will display your custom message instead of the default error page.
2. Redirect Back with a Custom Message
You can customize the behavior of the 419 error to redirect users back to the previous page with a flash message indicating that the CSRF token has expired.
Steps:
- Modify the Exception Handler:
Open theapp/Exceptions/Handler.php
file and modify therender
method to handle the 419 error in a custom way.
use Illuminate\Session\TokenMismatchException;
public function render($request, Throwable $exception)
{
if ($exception instanceof TokenMismatchException) {
// Redirect back with a custom message
return redirect()->back()->with('error', 'Your session has expired. Please try again.');
}
return parent::render($request, $exception);
}
2. Display the Flash Message in Your Views:
To display the flash message in your views, add the following code to your Blade templates (e.g., resources/views/layouts/app.blade.php
).
@if(session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
3. Test:
When a 419 error occurs, users will be redirected back to the previous page with the message “Your session has expired. Please try again.”
3. Return a JSON Response with a 419 Status Code
In some cases, you may want to return a JSON response with a 419 status code instead of redirecting to a different page. This can be particularly useful for API requests or AJAX calls.
Steps:
- Modify the Exception Handler:
Again, modify therender
method inapp/Exceptions/Handler.php
to detect when a 419 error occurs and return a JSON response.
use Illuminate\Session\TokenMismatchException;
public function render($request, Throwable $exception)
{
if ($exception instanceof TokenMismatchException) {
if ($request->wantsJson()) {
// Return a JSON response with a 419 status code
return response()->json(['message' => 'CSRF token has expired. Please reload the page and try again.'], 419);
}
// If not an AJAX request, redirect back with a message
return redirect()->back()->with('error', 'Your session has expired. Please try again.');
}
return parent::render($request, $exception);
}
2. Test:
When a 419 error occurs during an AJAX request, the response will be a JSON object with a 419
status code and a custom message:
{
"message": "CSRF token has expired. Please reload the page and try again."
}
Conclusion
Handling the 419 error in Laravel can be customized in various ways depending on the nature of your application. Whether you choose to:
- Display a custom error page,
- Redirect the user back with a helpful message, or
- Return a JSON response for API requests,
Laravel provides flexible tools to improve the user experience when dealing with session expirations and CSRF token mismatches.
By implementing the above solutions, you ensure that your users are informed and able to take appropriate action when their session expires, making your Laravel application more user-friendly and reliable.