Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 231
user225269 Avatar asked Dec 01 '12 08:12

user225269


People also ask

Why we use routes in Laravel?

Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.

How many types of routes are there in Laravel?

Route Parameters Laravel provides two ways of capturing the passed parameter: Required parameter. Optional Parameter.

How can I get current route in Laravel?

Accessing The Current RouteThe Route::current() method will return the route handling the current HTTP request, allowing you to inspect the full Illuminate\Routing\Route instance: $route = Route::current(); $name = $route->getName();


1 Answers

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

like image 61
afarazit Avatar answered Sep 21 '22 02:09

afarazit