Laravel 5.4 #21 : Roles and permissions (Part 3)

We continue with the roles and permissions section in Laravel. This part is going to be a bit dense, since we are going to do a lot of things. We will create a mini administration of users and we will be able to change their role and also we will be able to activate and deactivate users. All this, we can do it if our user has the administrator role.

First, we are going to start creating the controller. As usual, we will use the command that Laravel provide us.

And add this code:

It has 3 methods:

  • index: it sends the list of users to the view. And also the roles to show in the popup to change the role.
  • activeDeactive: it activates and deactivates the indicated user.
  • changeRole: it changes the role of the indicated user.

Create the view for the list of users and the popup for the change of role (index method):

Now, we are going to add the routes, but first we are going to create a middleware to check if the user has the administrator role:

And add this code, we can see it on the package documentation:

Register it:

Once we get this done, we can add the routes with the middleware:

Now, we are going to add in the header the administration link:

It is showed just if the user has the administrator role, this is done with the @role tag.

 

Open  app.js  and add this code to show the popup to change roles:

And execute this command, in order that the js of the public folder is updated:

The result would be this: