jerauf's avatar

Redirect back to previous page after login in Laravel 10

I'm having trouble figuring out how to redirect back to the previous page on login in Laravel 10 with Breeze. In previous versions, it was pretty simple. But it seems like there are several places that this needs to be changed and it's not quite clear where and what to replace. I assume that I use something like redirect(url()->previous()).

0 likes
9 replies
LaryAI's avatar
Level 58

In Laravel 8 and above, you can use the intended method to redirect the user back to their previous page after login. This method will redirect the user to the URL they were trying to access before being prompted to log in.

Here's an example of how to use it in a Breeze authentication controller:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            return redirect()->intended('/');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }
}

In this example, the intended method is called with the root URL (/) as the fallback URL. If the user was trying to access a different URL before being prompted to log in, they will be redirected to that URL instead.

Note that the intended method should only be used after a successful login attempt. If the login attempt fails, you should redirect the user back to the login page using the back method.

jerauf's avatar

I'm not trying to go to an intended URL. If a page that is not restricted was the last page accessed before clicking the login page, I want them to return to that page.

1 like
dcx's avatar

@jerauf Hi, i deleted my earlier response as I quickly realized I missed what you were trying to do, but also realized it's something i also needed to do!! I've done the below in the AuthenticatedSessionController - it looks/feels a bit hacky to me, but it works in fairness...more elegant solutions may come along of course..

    /**
     * Display the login view.
     */
    public function create(): Response
    {
        session()->put('previous_url', url()->previous());

        return Inertia::render('Auth/Login', [
            'canResetPassword' => Route::has('password.request'),
            'status' => session('status'),

        ]);
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request)
    {

        $previous_url = $request->session()->pull('previous_url', 'default');

        $request->authenticate();

        $request->session()->regenerate();

        return redirect()->intended($previous_url);
    }
1 like
limewater23's avatar
Level 1

@jerauf

use Illuminate\Support\Facades\Redirect;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {

        if (url()->previous() != url()->current()){

        Redirect::setIntendedUrl(url()->previous());

        }

        return view('auth.login');
    }

I used session to store the page URL before the "register" button is clicked (which leads to the registration page)

    public function create()
    {
        if (url()->previous() != url()->current()){

            Session::put('beforeregister', url()->previous());

            // Redirect::setIntendedUrl(url()->previous());

            }
        elseif(url()->previous() == url()->current()){

            Session::put('beforeregister',  redirect()->intended(RouteServiceProvider::HOME));
        }

        return view('auth.register');
    }

and u can call this session to redirect the previous page before you register, like in VerifyEmailController.php

    public function __invoke(EmailVerificationRequest $request)
    {

        if ($request->user()->hasVerifiedEmail()) {
            return redirect()->intended('?verified=1');
        }

        if ($request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return redirect(Session::get('beforeregister') . '?verified=1');
    }
}


I had this problem too back then, and this works for my website auth, I hope it can be helpful in your case.

2 likes
dcx's avatar

@limewater23 this is totally not the OP question IE no mention of register - but thumbs up i will use something like this too :)

1 like
dcx's avatar

@jerauf so my suggestion works for public pages where you just want to sign in (i.e sign in to add to cart for example) it also still works with a protected route by default because previous_url is in the session then removed when the local variable is set, yet still redirected there - indeed @wewhite solution works also if trying to access a protected route and login is forced (because of auth middleware intercept)...so both options are now there i guess..

silviososio's avatar

In the Livewire version of Breeze I solved the problem like this: in /resources/views/livewire/pages/auth/login.blade.php I added

public $coming_from = null;

public function mount(): void
{
    $this->coming_from = url()->previous() ?: route('home', absolute: false);
}

and changed the last login function line into

$this->redirectIntended(default: $this->coming_from, navigate: true);

Since "login" its called after the form is send, the "previous" url there is already "/login. The mount function instead is called the first time user accessed the login page, so there the previous url is the page he is coming from. Should be added some logic to verify that the previous url is indeed a page of your site.

Please or to participate in this conversation.