Laravel 5.4 #9 : Policies

We continue to move forward with Laravel and our blog. Today we are going to explain what the policies are and we will apply them to our project.

Policies are classes that allow us to handle the authorizations. That is, they allow us to restrict user access to certain parts of the project easily.

Create the policy:

Now we have to register the policy, open the file  app\Providers\AuthServiceProvider.php  and add the following line to the policies array:

As we can see, every policy has a related model.

Once registered, we have to create the restrictions to use them from the controller. Open the policy file:

The added methods do the same, check if the logged in user is the same as the creator. One will be for editing and the other one for deletion.

We eliminated almost all the middlewares, because with the policies that we will add now, they aren’t necessary. The controller will look like this:

Now we only need to create the view of the error that returns us when the condition of the policy isn’t true. Create a file called  403.blade.php  in  resources/views/errors :

I put that content, but you can put whatever you what.