Laravel 5.4 #20 : Roles and permissions (Part 2)

Today we are going to continue with the second part of roles and permissions in Laravel. What we are going to do is apply the restrictions depending on if the logged user has the permission or the role needed to do a particular action. We will change the Form Request, also some conditions that are in the view of the list of posts and also modify the policy of the posts.

First of all, go to the posts list view ( posts.blade.php ) and modify the if that restrict the access to the posts creation form and also modify the if that allows to see the edit and delete buttons:

As in my case, I do not want any user to access to create a post simply those who have the permission, restrict access by checking if the logged in user has the post_create permission. At the moment, it would be all administrators, but you can create another role (for example, writers) and have that permission and not others that would have administrators, that is, an intermediate role between administrators and users.

I also want administrators to edit or delete a post, so I put it in the check. If the logged in user is assigned the role of administrator, you can also delete and edit any post, you do not need to be the post creator.


Now, we are going to modify the authorize function of Form Request PostRequest.php . This file checks that you have the authorization to create or edit one post and also it validates that the sent data is correct.

Simply, it checks that the logged in user have the permission post_create or post_edit.


Modify the post policy (PostPolicy.php):

We have created a new create method to verify that users have the necessary permission to create a post, as we did previously with the form in the view. Also, you have to add the check to the update and delete method, this is so that users who are not the creators of the post but who have the permissions to edit and delete the post.

Finally, to apply the new method create we have to add this line, like we did with the others methods previously: