如何将未经授权的用户重定向到 Laravel 中的登录页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16131415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect an unauthorized user to the login page in Laravel?
提问by Ehsan Zargar Ershadi
I'm new to Laravel ( version 3 ), i do not know how to set Route and filters in Laravel so that any unauthorized user that is trying to access any url redirects to the login page (NOT the 404 error), in another word the default home page for unauthorized users is going to be the login page and for the authorized users it's going to be the dashboard.
我是 Laravel(版本 3)的新手,我不知道如何在 Laravel 中设置路由和过滤器,以便任何试图访问任何 url 的未授权用户重定向到登录页面(不是 404 错误),换句话说未授权用户的默认主页将是登录页面,授权用户的默认主页将是仪表板。
回答by Rok Burgar
If you are using laravel Auth class you can create an authorized route group. All routes that are defined there will be redirected if the user isn't logged in. Your router file will look something like this:
如果您使用 laravel Auth 类,您可以创建一个授权的路由组。如果用户未登录,所有在那里定义的路由都将被重定向。您的路由器文件将如下所示:
Route::get('/', array('as' => 'intro', 'uses' => 'intro@index'));
Route::get( 'login', array('as' => 'login', 'uses' => 'user@login'));
Route::get( 'logout', array('as' => 'logout', 'uses' => 'user@logout'));
// PROTECTED
Route::group(array('before' => 'auth'), function()
{
Route::get('dashboard', array('as' => 'dashboard', 'uses' => 'user@dashboard'));
});
// AUTH FILTER
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::to('login');
});
回答by Fernando Montoya
Just put a before filter in the declaration of the route like this
只需像这样在路由的声明中放置一个 before 过滤器
Route::get('edit_profile', array('before' => 'auth', function()
{
return View::make('profile.edit');
}));
The Auth filter exists by default in Laravel.
Laravel 中默认存在 Auth 过滤器。