phplaravelentrust

assign separate middleware to each method of a resource in laravel


I am using Zizaco/entrust laravel package as a ACL Manager for my project.

I know that for limit access to a route group via middlewares and assign a role (or permission) to it, I should do that like this:

Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {
    ....
});

But I want to assign separate permission to different routes(methods) of a resource controller.

I know that how can so that for whole resource but I can not implement it for each controller method:

Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {
        Route::resource('/post', ['middleware' => ['permission:manage-posts'], 'uses' => 'PostController']);

    });

I want to assing this permission to related method :

'post-create' => public function create ()  
'post-edit' => public function edit()

and so on.


Solution

  • You can assign middlewares in your controller's constructor:

    class Foo extends Conroller
    {
        public function __construct() {
    
            $this->middleware('post-create', ['only' => ['create']]);
    
            $this->middleware('post-edit', ['only' => ['edit']]);
        }
    }