简体   繁体   中英

Action filter for each method in Laravel controller

I am building quite an extensive app for a client and I will have to produce some kind of a group permission control. I decided to go with Cartalyst and their Sentry package.
So far so good!

Now the problem I am having is, what is the best way of detecting a user group permission, since there are more than just one, so I can't just use one filter and be done with it.

For example, I would do something like this:

For pages that need admin-level access

Route::group(array('before' => 'is_admin'), function()
{
       Route::get('admin', array('as'=>'admin', 'uses'=>'admin@index'));
       // Other methods that require admin-level access
});

For pages that need moretaor-level access and so on..

Route::group(array('before' => 'is_moderator'), function()

    {
           Route::get('orodja/plosca', array('as'=>'moderator', 'uses'=>'moderator@index'));
           // Other methods that require moderator-level access
    });

The problem I'm having with this approach is, that I would need to define a new route for every controller action and this really does not look like best practice to me.

Next I thought about registering all controllers with Controller::detect() and make them REST-full but I here the problem is, that I can apply filter only to the constructor method of a controller and not to a single action. What if I have method with different access-level in one controller..?

So my question is: What is the best way of getting around this problem and is there any way to apply a action filter to a single controller method, rather than to a controller constructor.

Thanks and sorry for my english!

You can attach a filter to all requests that start with a given URI (see the official doc on filters )

Route::filter('pattern: admin/*', 'auth');

Or you can attach a filter only to some actions within your controller:

$this->filter('before', 'auth')->only(array('index', 'list'));

On a side note, you don't have to create a route for every controller action you have. If you register your controller with Route::controller('admin::home'); it will fire automatically.

Another option would be that you define only one auth filter for all roles, then check for the different roles within the filter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM