Laravel 4 Auth redirect always to login page? /log

2020-07-10 11:39发布

I am using laravel for my web application and in routes.php I have:

// admin routes
Route::group(array('before' => 'auth'), function()
{
Route::controller('admin', 'UsersController');
});

I want to protect and check if the person is logged in , but this code always redirect to "/login" i want it to redirect to "admin/login" , can this be done?

标签: php laravel-4
3条回答
Evening l夕情丶
2楼-- · 2020-07-10 12:14

Yes. Add the following filter:

Route::filter('auth.admin', function()
{
    if (Auth::guest()) return Redirect::guest('admin/login');
});

I copied original auth filter delivered with Laravel.

Next, use your new filter:

Route::group(array('before' => 'auth.admin'), function()
{
Route::controller('admin', 'UsersController');
});
查看更多
成全新的幸福
3楼-- · 2020-07-10 12:17

Complete solution:

Route::filter('auth.admin', function() {
    // if not logged in redirect to the login page
    if (Auth::guest()) return Redirect::guest('admin/login');
});
Route::filter('auth.login', function() {
    // if already logged in don't show login page again
    if (Auth::check()) return Redirect::to('admin');
});

Route::get('admin/login', ['before' => 'auth.login', 'uses' => 'UsersController@getLogin']);

Route::group(['before' => 'auth.admin'], function () {
    Route::controller('admin', 'UsersController');
});
查看更多
祖国的老花朵
4楼-- · 2020-07-10 12:23

There is a default auth filter in the filters.php file, it should be like this:

Route::filter('auth', function($route, $request)
{
    if (Auth::guest()) return Redirect::guest('login'); // /login url
});

This filter (given above) will check if the user is not logged in then a redirect will occur and user will be sent to /login url and otherwise nothing will happen, user will be sent to the requested page.

Also, following filter is available by default and this filter just checks if the user is already logged in then (s)he will be redirected to / (home page) by default:

Route::filter('guest', function($route)
{
    if (Auth::check()) return Redirect::to('/'); // you may change it to /admin or so
});

This (guest) filter is used with /login as given below, so if a logged in user intended to log in then the user will be redirected to home page by default:

Route::get('login', array('before' => 'guest', 'uses' => 'UsersController@getLogin'));

Now, in your routes.php file you have following route declared:

Route::group(array('before' => 'auth'), function()
{
    Route::controller('admin', 'UsersController');
});

If everything is fine then this setup should work. If a logged out user tries to visit admin then user will be sent to login and these are by default available and should work.

查看更多
登录 后发表回答