I'm using Laravel 7.4, and I want to redirect the users to the page they came from after the login. I edited the file RedirectIfAuthenticated and added the redirect like:
return redirect()->intended(RouteServiceProvider::HOME);
But the problem is, it always redirected me to home. When I actually logged what the intended function returns, it always returns the url as website.com/email/verify. I'm 100% sure I don't redirect the users to that url, because I am logging in with an already verified user.
It might be some FW setup that I failed to notice, since I took over this project from another developer. I'll provide any more info if needed.
CodePudding user response:
Check for middleware maybe you are redirecting unverified users to email/verify
Then in your LoginController
create a protected function redirectTo()
and return url()->previous();
Your code will look like this
protected function redirectTo()
{
return url()->previous();
}
Or
Also you can add $this->redirectTo = url()->previous()
to your constructor
like this
public function __construct()
{
$this->redirectTo = url()->previous();
$this->middleware('guest')->except('logout');
}
Hope this helps
CodePudding user response:
If you dump dd(session()->all())
of a so-called "intended" page, you will see the following:
As you can see, Laravel store user's previously intended page at url['intended']
array element. So to imitate this behavior manually, you have to set this value manually where needed. In this case it's LoginController
:
public function showLoginForm()
{
session()->put('url.intended', url()->previous());
return view('admin.auth.login');
}
Now the original location has been stored, and later when the user log in, they will be redirected as declared in RedirectIfAuthenticated@handle
:
return redirect()->intended(RouteServiceProvider::HOME);
But what if the user went to the /login
page intentionally, or simply put, what if they refresh the page? url.intended
will have the value of route('login')
, then when user logged in, they will be redirected to login page and the infinite loop continues.
In that case, url.intended
should not have any value. RouteServiceProvider::HOME
value will be used as destination. There must be additional condition for that, let's say your site have login route named login
:
public function showLoginForm()
{
if (($url()->previous() != route('login')) {
session()->put('url.intended', url()->previous());
}
return view('admin.auth.login');
}
Case anything unclear, you may want to have a look at similar question