Creating and using Laravel policies

A policy in Laravel ensures you have authorization logic around a resource and its CRUD actions.

The best example of this is assigning all resources a user id and only that user can then view/edit/update/destroy. This makes the user only able to modify resources that they own.

Creating a policy

When creating a policy if you follow the Laravel naming convention it will automatically be discovered and linked.

php artisan make:policy NotePolicy --model=Note

Otherwise you have to register the policy in AuthServiceProvider by adding it to the $policies array:

protected $policies = [
   Note::class => NotePolicy::class,
];

Using the policy

Policies can be found in app/Models/Policies. Actions that can be used include viewAny,view,create,update,delete,restore and forceDelete.

If you used the --model flag when creating the action these methods are automatically created.

class NotePolicy
{
    public function show(User $user, Note $note): bool
    {
        return $user->id === $note->user_id;
    }
}

This will return false if the user’s id does not equal the one assigned to the note that is being viewed. It returns true if it does match.

Another option without the model passed in:

public function create(User $user): bool
{
    return $user->role === 'ADMIN';
}

Authorizing the action from the policy

Now to implement with policy actions you created

class NoteController extends Controller
{
    public function show(Request $request, Note $note)
    {
        $this->authorize('view', $note);
 
        //Show the note...
    }
}

The authorize method will throw a Illuminate\Auth\Access\AuthorizationException exception if the condition is not met.

This automatically gets converted into an HTTP 403 forbidden status response.

If you wanted to do a custom outcome:

class NoteController extends Controller
{
    public function show(Request $request, Note $note)
    {
        if ($request->user()->cannot('view', Note ::class)) {
             //Do something here....
             //Such as:
             abort(403);
           }

        //Show the note...
    }
}

Or the action doesn’t require a model to be passed in

class NoteController extends Controller
{
    public function show(Request $request, Note $note)
    {
        $this->authorize('view', Note::class);
 
        //Show the note...
    }
}

You can also attach as a route middleware:

Route::get('/note/{note}', function (Note $note) {
    //function
})->middleware('can:view,note');