'Redirect in session not working in Laravel

I am trying to do a basic login session in Laravel and I want the user not to be able to go to the login page once they are logged in. I tried to redirect it to the home page but it still shows my login page if I access it.

Do I have to add anything else?

This is the middleware that I used:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class UserAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if($request->path()=="login" && $request->session()->has('user'))
        {
            return redirect('/');
        }
        return $next($request);
    }
}


Solution 1:[1]

  1. Make sure you've actually registered your middleware (whether in app/Http/Kernel or with the routes/controller. Also ensure you run the middleware after Laravel's normal HTTP middleware otherwise it may not have started the session/fetched the user yet.

  2. I'm not sure $request->session()->has('user') is what you think it is - that's checking to see if the session has a key called user. You might want to check $request->user() instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dwight