如何添加过滤器全局,重定向除非是路由

时间:2014-03-20 20:15:51

标签: laravel

我在哪里添加过滤器如果用户已登录,则重定向到路由,除非该路由是a或b。

可以添加到:

App::before(function($request) { // });

所以我不需要为每条路线添加过滤器......如果我决定不会有一些除非?

Pseudo:

if logged in
    if no "property" then
        if not on "route1", "route2"
            redirect


App::before(function($request) { 

    if (Confide:check()) {

        if (confide:user()->prop == false) {

           //redirect (UNLESS?)))

        }

    }

});

1 个答案:

答案 0 :(得分:0)

是的,您可以执行以下操作:

App::before(function($request) { 
    if (Confide:check()) {

        if (confide:user()->prop == false) {

           if (! in_array(Route::getCurrentRoute()->getName(), array('route1', 'route2')))
           {
                //redirect
           }
        }
    }
});

无论如何,创建简单路由并使用组来过滤它们可能会更好:

/// Routes for those logged in with no prop
Route::group(['before' => 'loggedInAndNoProp'], function()
{
    Route::get('admin', ['as' => 'admin.index', 'uses' => 'AdminController@index']);
    Route::get('admin/users', ['as' => 'admin.users', 'uses' => 'AdminController@users']);
    Route::get('admin/store', ['as' => 'admin.store', 'uses' => 'AdminController@store']);
});

/// Routes for people not logged (will be resolved before normal logged in people)
Route::get('route1', ['as' => 'example1', 'uses' => 'ExampleController@example1']);
Route::get('route2', ['as' => 'example2', 'uses' => 'ExampleController@example2']);

/// Routes for people logged (falling back to them)
Route::group(['before' => 'auth'], function()
{
    Route::get('/', ['as' => 'admin.index', 'uses' => 'HomeController@index']);
    Route::get('users', ['as' => 'admin.users', 'uses' => 'UsersController@users']);
    Route::get('store', ['as' => 'admin.store', 'uses' => 'StoreController@store']);
});

/// Master fall back route, everything else comes to this one
Route::get('{any?}', ['as' => 'example3', 'uses' => 'ExampleController@example3']);