Skip to content

Laravel 11 Adds Policy Auto-Discovery to Models

While working on upgrading to Laravel 11, I came across an improvement I didn’t know was being made. A lot of attention has been paid to the config files and middleware being simplified in this release, but I hadn’t caught the fact that the framework now support the auto-discovery of policies.

I love this change!

The old way:

Prior to Laravel 11, you had to register your policies in the AuthServiceProvider.php file, ex:

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        User::class => UserPolicy::class,
        Client::class => ClientPolicy::class,
    ];
}

The new way:

In Laravel 11, if your policy file is located in \App\Policies\ and your Models are in \App\Models\, and the policy filename is named with the concatendated name of the model and the word “Policy”, this mapping will happen automatically.

Example:

\App\Models\UserPolicy will automatically be mapped to the \App\Models\User model.

If you need need to manually register a policy that doesn’t match this naming convention, you can still do so by using the Gate facade in the boot method of the AuthServiceProvider:

use App\Models\Order;
use App\Policies\OrderPolicy;
use Illuminate\Support\Facades\Gate;
 
/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Gate::policy(User::class, PeoplePolicy::class);
}

Question

My question to you – What use case have you run across where having a policy named differently than the model would be useful? Looking at my projects, they all align with that naming convention.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.