I wanted to redirect the user to the email verification page, when the canAccessFilament()
method failed. By default, Filament returns a 403
error.
Start with creating a new middleware by running php artisan make:middleware RedirectFilament
. Of course, you can choose the name yourself.
In your new middleware, write your redirection logic, here is mine as an example:
public function handle(Request $request, Closure $next){ $user = Auth::user(); if ($user instanceof FilamentUser && $user instanceof MustVerifyEmail) { if (! $user->canAccessFilament() && ! $user->hasVerifiedEmail()) { return redirect()->route('verification.notice'); } } return $next($request);}
Add your middleware to the config/filament.php
in the section middleware.auth
.
'middleware' => [ 'auth' => [ RedirectFilament::class, // <-- your middleware Authenticate::class, ], 'base' => [ EncryptCookies::class, AddQueuedCookiesToResponse::class, StartSession::class, AuthenticateSession::class, ShareErrorsFromSession::class, VerifyCsrfToken::class, SubstituteBindings::class, DispatchServingFilamentEvent::class, MirrorConfigToSubpackages::class, ],],
You need to change the middleware priority because the filament middleware will trigger first, leading to a 403
error.
To achieve this, checkout Sorting Middleware from the Laravel docs.
For me, my middleware had to come after \Illuminate\Session\Middleware\StartSession::class
so the user would be authenticated and before \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class
so the filament middleware doesn't trigger first.
protected $middlewarePriority = [ \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class, \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\RedirectFilament::class, // <-- your middleware \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class, \Illuminate\Routing\Middleware\ThrottleRequests::class, \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class, \Illuminate\Contracts\Session\Middleware\AuthenticatesSessions::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Auth\Middleware\Authorize::class,];
No comments yet…