Search code examples
phplaravellaravel-3

Using route filters in Laravel


I'm trying to use route filters in laravel to check whether a specific user has an access to a page:

Route::filter('check_roles', function()
{
    $current_url = URI::current();
    $access = 0;
    $nav = Session::get('navigation');
    foreach($nav as $k => $n){
      if(in_array($current_url, $n)){
        $access = 1;
      }
    }

    if($access == 0){
     return Redirect::to('home');
    }
    //problem is if the user has access to the page a blank page is returned

});

I'm using it in a route like this:

Route::get('admin/(:all)', array('before' => 'check_roles'));

The problem is if the user has access to the page a blank page is returned. How do I continue on with the default controller action if the user has access?


Solution

  • Replace Route::get() with Route::filter('pattern: admin/*', 'check_roles');.

    Now every time a request contains this pattern will be calling your check_roles filter. I think that this is what you currently need and not a Route::get(),

    You could use Route::get() on individual pages like

    Route::get('supersecret', array('before' => 'check_roles'), function() { return View::make('mysecret') });

    For more info Routing - Filters

    Updating to reflect my suggestion on the comment.

    You can create an Admin_Controller that will extends your Base_Controller and have your auth filter in the __construct().

    class Admin_Controller extends Base_Controller {
        public function __construct()
        {
            parent::__construct();
            $this->filter('before', 'auth');
        }
    }
    

    Have this contoller registered in your start.php (search for Autoloader, where your base_controller is mapped).

    And you could now extends your Admin_Controller whenever you want to protected your area.

    class Pages_Controller extends Admin_Controller {
        // do cool stuff
     }
    

    Hope that helps