Home >Backend Development >PHP Tutorial >How to Redirect Users Back to the Previous Page After Laravel Authentication?
Laravel: Redirecting to Previous Page After Login
Question:
How can I redirect a user back to the page they were trying to access before encountering a Laravel authentication filter?
Answer:
For Laravel 5.3 and above:
Redirect to the intended page using request()->intended(), e.g.:
// Auth middleware if (!Auth::check()) { return redirect()->intended('login'); } // Login action if (Auth::attempt(['email' => $email, 'password' => $password])) { return redirect()->intended('/'); }
For Laravel 5 up to 5.2:
// Auth middleware if (!Auth::check()) { return redirect()->guest('login'); }
// Login action if (Auth::attempt(['email' => $email, 'password' => $password])) { return redirect()->intended('defaultpage'); }
For Laravel 4:
// Auth filter Route::filter('auth', function() { if (!Auth::check()) { return Redirect::guest('login'); } });
// Login action if (Auth::attempt(['email' => $email, 'password' => $password])) { return Redirect::intended('defaultpage'); }
For Laravel 3:
// Auth filter Route::filter('auth', function() { if (!Auth::check()) { Session::put('redirect', URL::full()); return Redirect::to('/login'); } });
// Login controller public function get_login() { // ... } public function post_login() { // ... if (Auth::attempt($credentials)) { $redirect = Session::get('redirect'); Session::forget('redirect'); if ($redirect) { return Redirect::to($redirect); } else { return Redirect::to('defaultpage'); } } // ... }
The above is the detailed content of How to Redirect Users Back to the Previous Page After Laravel Authentication?. For more information, please follow other related articles on the PHP Chinese website!