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
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.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.