phplaravellaravel-middlewarelaravel-route

laravel 6 when login go to previous url not working


I'm using Laravel framework my previous version of laravel is 5.8 and in my middleware login

public function handle($request, Closure $next)
{
    if(Auth::check())
    {
        return $next($request);
    }
    else
    {
        Session::put('url.intended',URL::previous());
        return redirect('/login');
    }
}

and this is the controller login controller

if(Session::get('url.intended') <> '')
    return Redirect::to(Session::get('url.intended'));
else
    return redirect('/');

with this codes in laravel 5.8 everything was working great but when i upgrade to laravel 6 its not working any more i dont know why any help here thanks if i came from any link its always redirect me to / link


Solution

  • You should probably be letting the framework handle as much of this as possible. If you must use your own middleware and Controller method still let the framework handle this as it does best.

    Dealing with the intended URL is already something the framework is capable of doing itself and checks multiple conditions to figure this out. You can use the guest method of the Redirector to have it do this for you:

    return redirect()->guest('login');
    

    This will take care of the redirect to 'login' and set the url.intended in the session as needed.

    After login is successful you can redirect them to where they were trying to end up, 'intended', or a fallback url:

    return redirect()->intended('/');
    

    This will redirect to what it can find as the 'intended' and if not use a fallback. It will also remove the 'url.intended' key from the session as it is no longer of use. No need to set or check the session yourself.