Laravel - Authorization - Via The User Model
The App\Models\User
model that is included with your Laravel application includes two helpful methods for authorizing actions: can
and cannot
. The can
and cannot
methods receive the name of the action you wish to authorize and the relevant model. For example, let's determine if a user is authorized to update a given App\Models\Post
model. Typically, this will be done within a controller method:
user()->cannot('update', $post)) {
abort(403);
}
// Update the post...
}
}
If a policy is registered for the given model, the can
method will automatically call the appropriate policy and return the boolean result. If no policy is registered for the model, the can
method will attempt to call the closure-based Gate matching the given action name.