Laravel Redirect Back to Previous Page After Login

Published on June 29, 2020 27 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *