Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Karisme's avatar

Redirect to the last action after login

Hello,

I come to you because I want to redirect the user to this last action after connecting.

I use the auth middleware to redirect to the login if it is not authenticated.

Here is my RedirectIfAuthenticated middleware:

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return redirect()->intended('/');
        }

        return $next($request);
    }
}

It allows me to redirect the user to the url of this last action but without the right method and without the previous inputs filled.

Thank you for your answers.

0 likes
7 replies
Yorki's avatar

Try this

return redirect()->intended('/')->withInput();
Majeed's avatar

Try This way. Hope it will help

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {
            return back(); 
     //or return redirect()->back(); 
        }

        return $next($request);
    }
}
Karisme's avatar

Thank you for your answers.

Yorki the inputs are null after the connection.

Majeed but back() produce the same issue.

BishoyWagih's avatar

i have my solution, although i believe it is not the perfect one.

in the middleware you can fetch the last action before action by

$request()->getPathInfo();

so i created a session with this action..

 session(['intendedUrl' => request()->getPathInfo() ])

so after login you can redirect using this session..

Yorki's avatar

You might just make your own middleware to keep that data and use after user login.

class HoldLastRequestData
{
    public function handle($request, Closure $next, $guard = null)
    {
        if (!$request->is('*login')) {
            session(['last_request_data' => $request->all()]);
        }

        return $next($request);
    }
}

then

if (Auth::guard($guard)->check()) {
    return redirect()
        ->intended('/')
        ->withInput(session('last_request_data', []));
}
Karisme's avatar

Yorki, I just tested the solution it always happens the same thing. I am redirecting to the good url but not with the good path there the data.

Please or to participate in this conversation.