Categories: Development

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');

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago