Redirecting Back to Original Destination After Laravel Login
This functionality is frequently required in web applications. Laravel provides elegant solutions for essential features, leading to the question of whether this is a missed opportunity.
For Laravel 5.3 and Above
As Scott pointed out, a native method now exists:
return redirect()->intended('defaultpage');
For Laravel 5 Up to 5.2
Auth Middleware:
// redirect to "/login" and store the URL in session if (Auth::guest()) { return redirect()->guest('login'); }
Login Action:
// redirect back to intended page or default if not available if (Auth::attempt(['email' => $email, 'password' => $password])) { return redirect()->intended('defaultpage'); }
For Laravel 4
Although there wasn't official support in earlier versions, you can still implement it:
Auth Filter:
// redirect to "/login" and store the URL in session Route::filter('auth', function() { if (Auth::guest()) { return Redirect::guest('login'); } });
Login Action:
// redirect back to intended page or default if not available if (Auth::attempt(['email' => $email, 'password' => $password])) { return Redirect::intended('defaultpage'); }
For Laravel 3
An earlier approach involves storing the redirection in the session:
Auth Filter:
Route::filter('auth', function() { if (Auth::guest()) { Session::put('redirect', URL::full()); return Redirect::to('/login'); } if ($redirect = Session::get('redirect')) { Session::forget('redirect'); return Redirect::to($redirect); } });
Controller:
// login action public function post_login() { if (Auth::attempt($credentials)) { return Redirect::to('logged_in_homepage_here'); } return Redirect::to('login')->with_input(); }
This approach allows any component to set a redirection in the session for subsequent retrieval.
The above is the detailed content of How Can I Redirect Users Back to Their Original Destination After Laravel Login?. For more information, please follow other related articles on the PHP Chinese website!