//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);
How to check if a user is logged in, in a non middleware controller
in laravel?
auth Auth::guard
if (Auth::guard('api')->check()){ //will return true if logged in
//do this
}
else //if the user is not logged in
{
//do this
}