Laravel User Roles and Permissions
Roles and permissions are an important part of many web applications. In this tutorial we will see how we can implement user roles and permissions system in laravel. We will see it from scratch. We won't use spatie/laravel-permission package for doing it. But you can use spatie/laravel-permission to create this roles and permissions system in laravel 7.
It is important to add laravel user roles and permissions mechanism in our large scale application to give the permit to user to specific task. We will see from scratch laravel 7/6 user roles and permissions tutorial.
If you don't know how to create laravel 7/6 roles and permissions, then you are a right place. I will teach you from scratch laravel roles and permissions.But in this tutorial we will do user roles and permissions in laravel using our own custom code. So let's start how to implement & setup roles and permissions in Laravel.
Step 1 : Download Laravel Project
Open up your terminal and create a new Laravel project by typing in the following command
Step 2: Make Auth
If you are using laravel version 6 then run below command to make auth
If you are using below laravel version 6 then run below command to make auth
Step 3 : Make Model
We need model to make users roles and permissions. So let's create our model using below command.
As you may know, -m flag will create a migration file for the model. Now you’ll have two new migration files waiting for you to add new fields.
Step 4 : Edit the migration file
Step 5 : Adding pivot tables
For this first pivot table, we’ll create a new migration file for the table users_permissions. So run below command to create
For this pivot table between users and permissions, our schema should look like
Now let’s create a pivot table for users_roles.
The fields inside this table will pretty much the same as in users_permissions table. Our schema for this table will look like:
Under a particular Role, User may have specific Permission
For example, a user may have the permission for post a topic, and an admin may have the permission to edit or delete a topic. In this case, let’s setup a new table for roles_permissions to handle this complexity.
The Schema will be like:
Now run following command to create migration
Step 6 : Setting up the relationships
We’ll start by creating the relationships between roles and permissions table. In our Role.php , Permision.php.
App/Role.php
App/Permission.php
Step 7 : Creating a Trait
Inside of our app directory, let’s create a new directory and name it as Permissions and create a new file namely HasPermissionsTrait.php. A nice little trait has been setup to handle user relations. Back in our User model, just import this trait and we’re good to go.
app/User.php
Now open HasPermissionsTrait.php and paste those following code.
App/Permissions/HasPermissionsTrait.php
Here, we’re iterating through the roles and checking by the slug field, if that specific role exists. You can check or debug this by using:
Step 8 : Create CustomProvider
We’ll be utilizing the Laravel’s “can” directive to check if the User have Permission. and instead of using $user->hasPermissionTo().
we’ll use $user->can() To do so, we need to create a new PermissionsServiceProvider for authorization
Register your service provider and head over to the boot method to provide us a Gateway to use can() method.
now we have to register our PermissionsServiceProvider. Open this following file add this in providers array.
config\app.php
You can learn more about Laravel’s Gate facade at Laravel’s documentation. You can test it out as:
Step 9 : Add Dummy Data To Check
For creating roles and permissions tutorial, we need dummy data to check our user access. To create it paste this following code into this following slug.
App\Http\Controllers\PermissionController.php
After run blow route http://laravel7x.local/roles
Then you can login with blow account And Check role on Database
Email: darshan@gmail.com / darshanpatel@gmail.com
Pass: secrettt
Now goto this url and hit enter on your keyboard. Then you will see some dummy data to those following tables. To test this out in your routes files, we can die and dump on:
App\Http\Controllers\HomeController.php
public function test(Request $request)
{
$user = $request->user();
//will return true, if user has role
dd($user->hasRole('developer'));
// will return permission, if not null
dd($user->givePermissionsTo('create-tasks'));
// will return true, if user has permission
dd($user->can('create-tasks'));
exit;
}
Route::get('/test', 'HomeController@test');
Inside of our view files, we can use it like:
App\Http\Controllers\HomeController.php
public function testView(Request $request)
{
return view('testDeveloper');
}
resources\views\testDeveloper.blade.php
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
@role('developer')
Hello developer
@endrole
</div>
</div>
</div>
</div>
</div>
Route::get('/test-view', 'HomeController@testView');
This means only those user can see it whose role are developer. Now you can use many roles as you want.
Step 10 : Setup the Middleware
In order to protect our routes, we can setup the middleware to do so.
Add the middleware into your kernel & setup the handle method as follows
App\Http\Middleware\RoleMiddleware.php
Now we have to register this RoleMiddleware. So add this following code to register it.
App\Http\Kernel.php
Right now in our routes, we can do something like this
Note: Route Name set as the same database permissions table slug fields
Now you can use your controller like below to give user permission and access.
Route::get('/store', 'HomeController@store');
Route::get('/destory/{id}', 'HomeController@destory
');
Now only those user can access this route whose role is developer. Hope you will understand total procedure. Hope it will help you.