Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 835
A.B.Developer Avatar asked Dec 28 '25 13:12

A.B.Developer


1 Answers

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']]);
    }
}
like image 64
Angad Dubey Avatar answered Dec 31 '25 02:12

Angad Dubey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!