I read here that in Laravel we can use the can
method instead of the traditional middleware call on a route. https://laravel.com/docs/11.x/authorization#middleware-actions-that-dont-require-models
use AppModelsPost;
Route::post('/post', function () {
// The current user may create posts...
})->can('create', Post::class);
Now the traditional method for middlewares looks like this:
Route::post('/post', function () {
// The current user may create posts...
})->middleware('can:create,AppModelsPost');
I really like this can
method and it would be nice to be able to replace middleware calls for update too to be consequent:
use AppModelsPost;
Route::put('/post/{post}', function (Post $post) {
// The current user may update the post...
})->middleware('can:update,post');
Is there a way to do this? The documentation does not contain anything about this…
2
Answers
Using the
can
Method for Update Routes->can('update', 'post')
: Specifies the authorization policy to be applied. Here,'update'
is the policy method, and'post'
is the parameter passed to that method. Laravel will automatically inject the model instance from the route parameter and perform the authorization check.In your
PostPolicy
, you should have a method like this:There are few steps you need to follow.
Create & get registered your
Policy
class.With this command create a Policy-class. The generated policy will be placed
in the
app/Policies
directory.This class look like this.
Then register the
policy-class
to theboot
method of your application’sAppServiceProvider
like this.And finally you can use the
can
in the route to use thisPostPolicy
class like this.N:B :-
Post
model must have aforeign-key
nameduser_id
upon whichupdate
authorization will be matched.If no matched users found then an HTTP response with a 403 status will be returned.Policy
Generating Policies
&Registering Policies
section of the docs.