Apply Policy to Resource Controller

2019-06-17 06:30发布

问题:

I have a CRUD Resource defined via Route::resource('User', 'UserController').

Since it is possible to generate CRUD Gates and Policies, is there a way to apply such a Gate / Policy, so that the corresponding gate / policy is applied to a specific route?

I think that would be an elegant way, since my polices would match my routes. I'm looking for a method like applyPolicy or something simliar:

Route::resource('User', 'UserController')->applyPolicy()

Otherwise I would have to add each policy to each action, which doesn't seem so elegant.

回答1:

Take a look at the authorizeResource(Model::class) method.

An example would be in your controller's constructor:

public function __construct()
{
    $this->authorizeResource(Task::class);
}