Laravel 5.4 #19 : Roles and permissions (Part 1)

As I mentioned in several posts, I was going to write about how to add a role system in our project, the first post I’ll write about this will be this one. I don’t know how many parts it will have, but it will have several.

Today we will add the necessary package to be able to manage the roles and permissions of our project with Laravel.

Package installation

We are going to install the Spatie’s laravel-permission. This installation guide is based on the package documentation.

First, download it:

When it finishes, we have to add to the providers array of  config/app.php  this line:

Publish the migration and execute it:

Publish the configuration file:

And it would already be installed, we simply need to add these lines to the User.php  model so we can start using it:

 

Modification of seeders

Currently in our seeders aren’t considered roles and permissions, that the reason why we are going to generate some roles and permissions and assign to the users that are generated.

Let’s create seeders for roles and permissions:

Open the  PermissionsTableSeeder.php  and add this code, this is an example, you can add the permissions we want:

Open the  RolesTableSeeder.php  and add this code, this is an example, we can add the roles we want and assign the permissions we want:

And modify the seeder of the users:

We are generating 5 users. For the first user generated, we assign the role of administrator and the others the user role. Then, we generate 8 posts that are associated with the user with id number 1 (the administrator).

Modify  DatabaseSeeder.php :

Refresh the database (delete all content) and execute the seeders with this command:

 

 

Now we are going to assign new users the user role. Open  RegisterController.php and modify the create method: