Skip to content

Gates and Policies in Laravel

Gates

How to Create a Custom Gate

Laravel service provider when you need to register a component or a service. Following that convention, let's go ahead and define our custom gate in the app/Providers/AuthServiceProvider.php as shown in the following snippet.

Code_image

In the boot method, we've defined our custom gate:

Code_image

While defining a gate, it takes a closure that returns either TRUE or FALSE based on the authorization logic that's defined in the gate definition.

How to Use Our Custom Gate

In the routes file routes/web.php, let's add the following route.

Code_image

Let's create an controller file app/Http/Controllers/PostController.php as well.

Code_image

In most cases, you'll end up using either the allows or denies method of the Gate facade to authorize a certain action. In our example above, we've used the allows method to check if the current user is able to perform the update-post action.

Policies

How to Create a Custom Policy

we'll create a policy for the Post model that will be used to authorize all the CRUD actions. I assume that you've already implemented the Post model in your application; otherwise, something similar will do.

Code_image

we've supplied the --model=Post argument so that it creates all the CRUD methods. In the absence of that, it'll create a blank policy class. You can locate the newly created policy class at app/Policies/PostPolicy.php

Code_image

To be able to use our policy class, we need to register it using the Laravel service provider as shown in the following snippet.

Code_image

We've added the mapping of our policy in the $policies property. It tells Laravel to call the corresponding policy method to authorize the CRUD action.

Use the Policy in a controller

we can use it in our controllers to control access to resources. For example, suppose we have a PostController with an update() method that allows users to update a post:

Code_image

This means that Laravel will use this policy to authorize any actions related to the Post model.