Automatic Policy Resolution in Laravel 5.8

In Laravel 5.8 the automatic policy resolution is a new feature. So in the 5.8 version you don’t need to register your policies in AuthServiceProvider it will be automatically added. Let’s see how it works. 

Create a policy with artisan command.

php artisan make:policy PostPolicy --model=Post

Type necessary methods and rules in the policy as shown below.

use App\User;
use App\Post;

class PostPolicy
{
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

After this step normally we need to register policies as given below.

use App\Post;
use App\Policies\PostPolicy;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        Post::class => PostPolicy::class,
    ];

In the Laravel 5.8 version here is how guessing or automatically registering policies work.

protected function guessPolicyName($class)
{
    return dirname(str_replace('\\', '/', $class)).'\\Policies\\'.class_basename($class).'Policy';
}

Your policies will be located in the app/Policies directory and the name will be the same as the model. 


Correct location: app/User.php -> app/Policies/UserPolicy.php

Instead of the above given location if your policies and models are in some other directories or path you need to specify your own logic for guessing or use the same $policies array in AuthServiceProvider.