Marianne Hartigan
Marianne Hartigan

Reputation: 25

Laravel 11 map model to policy of different name

I would like to map a model to a policy of a different name. It used to be done in AuthServiceProvider.php:

protected $policies = [
    'App\Models\Model' => 'App\Policies\ModelPolicy',
];

But now there is no AuthServiceProvider.php in Laravel 11.

I have read that it can be done in bootstrap\app.php but I have not been able to find out how to do this. If anyone knows how that would be great.

Upvotes: 0

Views: 66

Answers (1)

Raghavendra N
Raghavendra N

Reputation: 6694

In laravel 11, the policies are auto discovered based on the naming conventions. So if you have a UserPolicy, then it will be automatically mapped to the User model. Make sure you keep your policies in either app/Models/Policies or app/Policies directory.

If are not following the above name/directory conventions, then you can manually register the policies in the boot method of your AppServiceProvider.

See the below example on how to manually register the policies using Gate facade. This example is from Laravel Docs.

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

Upvotes: 0

Related Questions