Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel middleware check if user is logged in

//Create the middleware if not exists
class RedirectIfAuthenticated 
{ 
    public function handle(Request $request, Closure $next, ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
              	//redirect to where you want
                return redirect(url('dashboard'));
            }
        }
        return $next($request);
    }
}


//Then use the middleware in pages you don't want logged in users to access like this
Route::get('/register', [AuthController::class, 'register'])->name("register")
    ->middleware(RedirectIfAuthenticated::class);

 
PREVIOUS NEXT
Tagged: #laravel #middleware #check #user #logged
ADD COMMENT
Topic
Name
2+1 =