😇Bài viết gốc

https://acquaintsoft.com/blog/laravel-permission-demo

Source code

What is Laravel-permission?

Not every user needs to have an access to all the data in the database. Let’s take the example of a college website. The access to the data and permissions allowed to a teacher will be different from that of a student. Why? Because their roles and responsibilities are different.

Laravel-permission allows you to do the same with your database. It lets you manage users’ roles and permissions in your database. Let’s see how you can do the same step-by-step.

Prefer watching a video instead? No worries! Just follow along with the video below.

Step 1. Install Laravel project

To keep things simple, I am going to show you how to install Laravel using composer provided that you already have WAMP or XAMPP installation and Composer on your computer.

composer create-project laravel/laravel laravel-permission-demo
cd laravel-permission-demo

Once the application is started after you run the above-mentioned command, you have to start Laravel’s local development server. For that, use Artisan CLI’s serve command.

Now you have to create a new database in PhpMyAdmin and add the database details in the root directory .env file. We are going to use MySQL.

Step 2. Install Breeze

What is Breeze?

Whenever you go to any website, you will often see login and signup forms which also reset and confirm passwords, and verify your email. Lararvel Breeze helps you do exactly this with your website in a simple way.

Now, if you want to assign permissions to your users, you need to have a proper login system. So here is how you can install Breeze and publish the authentication views, routes, controllers, and other resources.

Now it’s time to compile the frontend assets of your application. For a new terminal, run: -

For database migration: -

Once your migration users and tables are created in your database, you can see the following.

Now you can check your application’s login and register URLs

For login

For register

Step 3. Install Laravel-permission package

Why do we use Laravel permission?

Not everybody needs to get access to everything in your database. Otherwise, you may be running the risk of jeopardizing your invaluable data. Thus, Laravel permissions give you the power to limit access to data as per the roles of the user. So next we will cover how to install the Laravel-permission package.

I would recommend you to first go and check the prerequisites page for user models. Please also check that you don’t have a file named config/permission.php because this package will publish a file with that name. If you have one, then rename it.

Run this command.

You can even manually add the service provider in your config/app.php file. However, it is optional.

Now publish the migration and the config/permission.php config file using: -

Here I want to point out a couple of things: -

  1. If you want to use teams feature, updates your config/permission.php file and set 'teams' => true. If you want to use a custom foreign key for teams, you should also change teamforeignkey. I also recommend you to check the advanced section of docs on UUID steps if your are using UUIDs.

  2. Clear your config cache as it is a bad practice to do config-caching while developing. For clearing caching configurations locally, use these commands: -

Once the config and migration have been published and configured, create the tables for this package by running: -

Add all the required traits to your user model. You can refer to the Basic Usage section of the docs to know how to get started using the feature of this package.

Add this line user.php

After that user HasRoles in class.

Step 4: Create permission, roles, and screens

What is a role?

The role is the authority we assign to someone for access to the data. The higher someone’s role is, the more permissions he will get. Usually, we assign roles as per the rank of the user. For example - executives may get the role of super admin to do anything he wants. Here is how you can create permissions, roles, and screens.

First, we will create a database seeder for the super admin user.

Use spatie classes in seeder file.

Now, replace this code in database\seeder\BasicPermissionSeeder.php

So, just to recap, till now we have created a super admin user, a test user, and an admin user and assigned to each one of them permissions as per role 1, role 2, and role 3 respectively.

Next, you have to run the database seed command to insert data into the database.

Grant Super-Admin access

Gate has allowed all the permissions to the super-admin. We are using Laravel’s default password for the super-admin, which is “password”.

Add below a Gate::before checking in your AuthServiceProviderboot function.

Add permission check

Now all the users have full access to the application as we have not added permission to check Laravel’s default can function.

In Blade directives:

Next, we are going to implement CRUD (screen) for the permission and roles.

Step 5: Permission management CRUD

Follow these steps to create permission CRUD for our Laravel Admin panel.

For the permission

Step 1: Create a model

We are going to start by creating a model for permission CRUD. You can create your model using the make:model Artisan command. It will create a Permission.php file in app/Models folder.

We can also create the models and controllers manually.

Next is to extend our permission model with Spatie\\Permission\\Models\\Permission and update the model with the below code.

app/Models/Permission.php

Step 2: Create a controller

The make:controller Artisan command is used to create the controllers.

The --resource option is used to quickly create a controller to handle create, read, update, and delete (“CRUD”) operations.

Step 3: Add routes

Extend controllers in web.php file.

Add resource route in web.php. We are using auth middleware and Admin namespace.

So, we have completed the creation of CRUD for permission. Now add the permission link below the Navigation Links on navigation.blade.php.

resources/views/layouts/navigation.blade.php

For mobile navigation

Update index function with permission paginating.

app/Http/Controllers/Admin/PermissionController.php

Create the index.blade.php view file inside the admin/permission folder.

resources/views/admin/permission/index.blade.php

This page has create, read, and update links. We have also added a delete button with the form. Update the destroy function with the below code: -

app/Http/Controllers/Admin/PermissionController.php

Step 6: Create operation

Update the create function with the below code and create create.blade.php view file.

app/Http/Controllers/Admin/PermissionController.php

resources/views/admin/permission/create.blade.php

Navigate the http://127.0.0.1:8000/admin/permission/create URL in the browser.

The submit action will call the store function. So copy the below code to the store function

app/Http/Controllers/Admin/PermissionController.php

The $request->validate is used to validate the create form.

Step 7: Update operation

We will use two functions used for the update. The edit function for form display and update function to save the form.

app/Http/Controllers/Admin/PermissionController.php

resources/views/admin/permission/edit.blade.php

Step 8: View operation

This is the final step for our permission CRUD. The show function is used for the view operation.

app/Http/Controllers/Admin/PermissionController.php

resources/views/admin/permission/show.blade.php

We have successfully created our first Laravel CRUD. This permission CRUD is open for all authenticated users. So for the next part, we need to add permission-based access restriction to our permission CRUD.

For the Roles and User

Step 1: Create Model

app/Models/Role.php

Step 2: Create a controller

Step 3: Add Routes

We have added two routes: -

  1. role

  2. user

For mobile navigation

  1. Roles

Update index function with permission paginating.

app/Http/Controllers/Admin/RoleController.php

Create the index.blade.php view file inside the admin/role folder.

resources/views/admin/role/index.blade.php

Don’t forget the run the npm run dev to rebuild the CSS.

This page has create, read, and update links. We have also added a delete button with the form. Update the destroy function with the below code.

app/Http/Controllers/Admin/RoleController.php

2 . User

Create the index.blade.php, create.blade.php, edit.blade.php, and show.blade.php files inside the admin/user folder.

resources/views/admin/user/index.blade.php

app/Http/Controllers/Admin/UserController.php

Step 6: Create operation

  1. Role

Update the create function with the below code and create create.blade.php view file. The Permission::all() is used to list the permission on create page.

app/Http/Controllers/Admin/RoleController.php

resources/views/admin/role/create.blade.php

Navigate the http://127.0.0.1:8000/admin/role/create URL in the browser.

The submit action will call the store function. So copy the below code in the store function.

app/Http/Controllers/Admin/RoleController.php

2 . User

Users, in this case, are anyone who asks for permission to your database. They are usually the people in your organization.

app/Http/Controllers/Admin/UserController.php

Extend model in user controller

resources/views/admin/user/create.blade.php

Step 7: Update operation

  1. Role

We will use two functions used for the update. The edit function for form display and update function to save the form.

app/Http/Controllers/Admin/RoleController.php

Export spatie role and permission class

resources/views/admin/role/edit.blade.php

  1. User

You need to make sure that the users of your database get the right set of permissions so that the security of your data remains strong.

resources/views/admin/user/edit.blade.php

app/Http/Controllers/Admin/UserController.php

8. View operation

  1. Role

Here, with this operation, we will be viewing the roles of the users to whom you have granted the permissions.

app/Http/Controllers/Admin/RoleController.php

resources/views/admin/role/show.blade.php

  1. User

Here is how you can view users of your database along with their other details such as their assigned permissions.

app/Http/Controllers/Admin/UserController.php

resources/views/admin/user/show.blade.php

Add link in the dropdown

Add function in user controller

app/Http/Controllers/Admin/UserController.php

If you are wondering about the source of this code and want to have a look, then here is the link.

Github Link - Laravel Permission Demo

If you are wondering about the source of this code and want to have a look, then here is the link.

https://permission-demo.acquaintsoft.com/

Here is the demo link. Have a look to see it all in even more detail.

Conclusion

Assigning permissions to users is necessary for sake of the security of your data. If you have followed along with the above-mentioned steps, I know that you also would have been able to create permissions and assign roles easily.

Last updated

Was this helpful?