If you're making use of policies in Laravel for authorization, here's how to register them.
As an example, let's imagine a Comment
model. We want to create a policy for it.
php artisan make:policy CommentPolicy
By generating a policy this way, we've:
Policies
directoryModelPolicy
And because of this, using auto-discovery, Laravel has already registered your policy against that model for you. That's right, nothing left to do!
If you're using a different structure within your application or prefer not to name Policies within Laravel conventions, you can, of course, manually register policies.
In a service provider, typically AppServiceProvider
:
public function boot(): void
{
Gate::policy(Comment::class, CommentPolicy::class);
}
You can customize the policy discovery logic using the guessPolicyNamesUsing
method via the Gate
facade.
use Illuminate\Support\Facades\Gate;
Gate::guessPolicyNamesUsing(function (string $modelClass) {
return 'PolicyFor' . $modelClass;
});
This assumes we want to discover policies named PolicyFor[Model]
. Unlikely, but now you know how to change the logic.