Laravel User Role Permission

In the Laravel web application, user role permission is the most important part of a developer. Because in an application, we use too many user credentials. So, we are not giving the same permission to every user. Now I am going to show you how to create multiple user roles and their permissions step by step below.


Step1: First, install these two in your CMD run on your project directory.

composer require spatie/laravel-permission

composer require laravelcollective/html
 

Step2: Add This in your config/App.php file.

Spatie\Permission\PermissionServiceProvider::class,
 

Step3: Now add middleware in App/Http/Kernel.php file.

protected $routeMiddleware = [
'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
‘permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
];

Step4: Add this in your Routes\web.php file

Add this in your Routes\web.php file
Route::group(['prefix' => 'role','middleware' => 'auth'], function(){
Route::get('/',[
'as' => 'role',
'uses' => 'RoleController@index',
]);
Route::post('/store',[
'as' => 'role_store',
'uses' => 'RoleController@store',
]);
Route::get('/edit/{id}',[
'as' => 'role_edit',
'uses' => 'RoleController@edit',
]);
Route::post('/update/{id}',[
'as' => 'role_update',
'uses' => 'RoleController@update',
]);
Route::get('/{id}',[
'as' => 'role_view',
'uses' => 'RoleController@show',
]);
});

Step5: Now create these four tables by the migration process

Table 1: model_has_roles

Here is the screenshot.


Table 2: roles


Table 3: permissions

Here is the screenshot.


Table 4: role_has_permissions


Step6: Create a Role Controller by CMD through this command.

php artisan make:controller RoleController

Step7: After Create RoleController put this in it.

use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
function __construct()
    {
         $this->middleware('permission:role-list|role-create|role-edit|role-delete', ['only' => ['index','store']]);
         $this->middleware('permission:role-create', ['only' => ['create','store']]);
         $this->middleware('permission:role-edit', ['only' => ['edit','update']]);
         $this->middleware('permission:role-delete', ['only' => ['destroy']]);
    }
public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:roles,name',
            'permission' => 'required',
        ]);
        $role = Role::create(['name' => $request->input('name')]);
foreach($request->permission as $each_permission){
DB::table('role_has_permissions')->insert(
['permission_id' => $each_permission, 'role_id' => $role->id]
);
}
        return redirect()->route('role')
                        ->with('success','Role created successfully');
    }

Step8: Now add this for handling the exception in add/Exceptions/Handler.php file.

public function render($request, Exception $exception)
    {
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->json(['User have not permission to access this page.']);
}
        return parent::render($request, $exception);
    }

Then run the project and get the importance of roles.

In this post, you can see how easily we can manage the roles and permissions in the Laravel web application. If you Google “Laravel User Role Permission”, you will find lots of suggestions and techniques. But I made it simple for all the Laravel developers.

Conclusion:

This is very important for Laravel development. If you have any feedback or suggestions, please share the same in the comment sections.

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.