Use-
return redirect()
->back();
Normally, after successfully logged in, the best way to redirect to protected page is intended().
Hi, do you guys know how to redirect back to previous page after login success? There is an answer for it at stackoverflow but I'm kinda confuse about which file he is refering to https://stackoverflow.com/questions/15389833/laravel-redirect-back-to-original-destination-after-login
answered by vFragosop
Simply put,
On auth middleware: (what is the file name he is refering to? RedirectIfAuthenticated.php?)
// redirect the user to "/login"
// and stores the url being accessed on session
if (Auth::guest()) {
return redirect()->guest('login');
}
return $next($request);
On login action: (same here, what is the file name? LoginController.php?)
// redirect the user back to the intended page
// or defaultpage if there isn't one
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('defaultpage');
}
protected $redirectTo = 'your-url';
Yes, I understand that line of code but the problem is that code is static, you can only redirect back to your predifined url It can't redirect back to previous page
and I found this solution by Scott Byers, but it is not working too
Laravel >= 5.3 The Auth changes in 5.3 make implementation of this a little easier, and slightly different than 5.2 since the Auth Middleware has been moved to the service container. Modify the new Middleware auth redirector
/app/Http/Middleware/RedirectIfAuthenticated.php
Change the handle function slightly, so it looks like:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/home');
}
return $next($request);
}
(Solution) I managed to solve it (but I'm not that sure if this is the correct way to do it) in the AuthenticatesUsers.php file
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
return back(); //add this line of code
}
and btw I found this RedirectsUsers.php file, but I have no idea how it work so I don't touch it
<?php
namespace Illuminate\Foundation\Auth;
trait RedirectsUsers
{
/**
* Get the post register / login redirect path.
*
* @return string
*/
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/';
}
}
Please or to participate in this conversation.