Laravel Redirect Back to Previous Page After Login

In this article, I’m going to share to how redirect back to the previous page after login. Let’s see some solutions:

Table of Contents

  1. Solution 1
  2. Solution 2

Solution 1

The LoginController path is app/Http/Controllers/Auth/LoginController.php.

In the LoginController, add this showLoginForm() function:

public function showLoginForm()
{
    if(!session()->has('url.intended'))
    {
        session(['url.intended' => url()->previous()]);
    }
    return view('auth.login');
}

This function will set the “url.intended” session variable. Laravel uses this variable to look for the page in which the user will be redirected after login.

Solution 2

Inside LoginController, add this line to the __construct() function:

$this->redirectTo = url()->previous();

The full code will look like:

public function __construct()
{
    $this->middleware('guest')->except('logout');
    $this->redirectTo = url()->previous();
}

That’s it. Thanks for reading.