For Laravel 5.3 and above
勾选下面的Scott's answer.
对于Laravel 5至5.2
简单地说,
On auth middleware:
// 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:
// 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');
}
For Laravel 4 (old answer)
在回答这一问题时,框架本身没有得到官方支持.现在您可以使用下面bgdrl指出的方法:(I've tried updating his answer, but it seems he won't accept)
在身份验证筛选器上:
// redirect the user to "/login"
// and stores the url being accessed on session
Route::filter('auth', function() {
if (Auth::guest()) {
return Redirect::guest('login');
}
});
On login action:
// 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');
}
对于Laravel 3(更老的答案)
You could implement it like this:
Route::filter('auth', function() {
// If there's no user authenticated session
if (Auth::guest()) {
// Stores current url on session and redirect to login page
Session::put('redirect', URL::full());
return Redirect::to('/login');
}
if ($redirect = Session::get('redirect')) {
Session::forget('redirect');
return Redirect::to($redirect);
}
});
// on controller
public function get_login()
{
$this->layout->nest('content', 'auth.login');
}
public function post_login()
{
$credentials = [
'username' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($credentials)) {
return Redirect::to('logged_in_homepage_here');
}
return Redirect::to('login')->with_input();
}
将重定向存储在会话中有一个好处,即即使用户未键入其凭据,或者他没有帐户,必须注册,也可以保持重定向.
这还允许除了Auth之外的任何东西在会话上设置重定向,它将神奇地工作.