mkastoun / laravel-419-handler
Graceful handling of Laravel 419 session expired errors.
v1.1.1
2025-03-27 10:38 UTC
Requires
- php: >=8.0
- illuminate/support: ^9.0|^10.0|^11.0
Requires (Dev)
- orchestra/testbench: ^7.0|^8.0|^9.0
README
Gracefully handle 419 Page Expired
errors in Laravel using a clean, package-based trait that integrates into your Handler.php
.
β¨ Features
- Handles
TokenMismatchException
(CSRF/session expiration) - Clean
trait
-based integration (no overriding core Laravel handlers) - Redirects with flash messages (web)
- JSON error response (API)
- Configurable behavior
π¦ Installation
Via Composer:
composer require mkastoun/laravel-419-handler
βοΈ Publish Configuration
php artisan vendor:publish --provider="Laravel419Handler\Laravel419HandlerServiceProvider" --tag=config
Configuration (config/laravel419.php)
return [ 'redirect_on_web' => '/', 'flash_message' => 'Your session has expired. Please try again.', 'auto_refresh_on_back' => true, 'json_response' => [ 'message' => 'Session expired. Please try again.', 'status' => 419, ], ];
π§© Integration
In your App\Exceptions\Handler.php
:
- Import and use the trait:
use Laravel419Handler\Traits\HandlesTokenMismatch; use Illuminate\Session\TokenMismatchException; class Handler extends ExceptionHandler { use HandlesTokenMismatch; public function render($request, Throwable $e) { if ($e instanceof TokenMismatchException) { return $this->handleTokenMismatch($request, $e); } return parent::render($request, $e); } }
- In your Blade layout, show the flash error (Optional):
@if(session('error')) <div class="alert alert-danger"> {{ session('error') }} </div> @endif
π§ͺ Testing
composer test
π License
MIT
π€ Contributing
PRs welcome! Please submit issues, ideas, and improvements to help others benefit from this package.
π§ Why Not Middleware?
While catching 419s via middleware is sometimes possible, itβs not 100% reliable because TokenMismatchException
is thrown before controller or middleware logic in some cases. Using a trait inside the exception handler guarantees full coverage β safely and cleanly.