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.
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);
}
For the above to work in Laravel 11, also add the following imports and trait to your controller:
use Illuminate\Routing\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class TaskController extends Controller
{
use AuthorizesRequests;