Laravel authorization and roles permission management
Tags: laravel, webdev
Published: 2019-07-14 07:35:51

<hr>
You can read this post on Medium,
https://medium.com/swlh/laravel-authorization-and-roles-permission-management-6d8f2043ea20?source=friends_link&sk=8c0dbf347d4d765ac2b276e4a53c5a4f
<hr>
In many web projects, we have different user roles interacting with the system. Each role has its own permission. Every feature of the system can be enabled or disabled for these roles. We can define users permissions in our codes and check if they are authorized to do the requested action or not. A better way, mostly in more flexible systems, is to create a role and authorization management system. I’ll explain how to implement a Laravel authorization system and define users permission based on their roles.
<hr>
In this post, firstly we manage users in groups we called roles. Every role has different permissions. In order to avoid permissions conflict, we assume each user has only one role. Secondly, Laravel authorization implemented by a middleware. This middleware checks for the user’s role permission and authorizes user requests.
### CREATING ROLES AND PERMISSIONS
In order to implement Laravel authorization, we will create roles and permissions table. To assign a role for users, we create a roles table. The migration for roles table is as simple as this:
<pre>
Schema::create(‘roles’, function (Blueprint $table) {
 $table->increments(‘id’);
 $table->string(‘name’);
 $table->string(‘description’)->nullable();
 $table->timestamps();
});
</pre>
We have an ID and name for roles. All users will be managed in these roles. There is also a description field, because you may need a short note on roles to describe each role for yourself.
After that, we add a foreign key, role_id, in the user table. Adding this field to the default user model helps us for Laravel authorization.
<pre>
$table->unsignedInteger(‘role_id’)->index();
$table->foreign(‘role_id’)->references(‘id’)->on(‘roles’);
</pre>
<hr>
Now let’s talk about the permissions table. Every request leads to a method of a controller. So we store a list of all methods and their controller’s name in the permissions table. Later, we explain how we gather this list and how we check users authorization in Laravel by this permissions table.
<pre>
Schema::create(‘permissions’, function (Blueprint $table) {
 $table->increments(‘id’);
 $table->string(‘name’)->nullable();
 $table->string(‘key’)->nullable();
 $table->string(‘controller’);
 $table->string(‘method’);
 $table->timestamps();
});
</pre>
Finally, a relationship created between roles and permission.
<pre>
Schema::create(‘permission_role’, function (Blueprint $table) {
 $table->unsignedInteger(‘permission_id’);
 $table->unsignedInteger(‘role_id’);
$table->foreign(‘permission_id’)
 ->references(‘id’)
 ->on(‘permissions’)
 ->onDelete(‘cascade’);
$table->foreign(‘role_id’)
 ->references(‘id’)
 ->on(‘roles’)
 ->onDelete(‘cascade’);
$table->primary([‘permission_id’, ‘role_id’]);
});
</pre>
We created a complete users->roles->permissions architecture. After that, an access list will be stored in these tables. So, we can easily implement Laravel authorization by checking requests against this list.

Read Laravel migration documentation for further information about creating tables.
<hr>
### CREATING AN ACCESS LIST FOR USER PERMISSIONS
The whole purpose of this post is about being dynamic. Especially, in systems with a different type of roles. We need to create a list of permissions in the system. Also, this list must be updated as the system developed. List of controllers and methods is a good representation of all permissions in the system. Every route is leading to a method of a controller. So, it’s a good idea to make a list of permissions using the routes list.
In order to do that, I used a Laravel database seeder. Firstly, let’s write a role seeder. It creates basic roles we need and stores them in the roles table. Running this artisan command will create RolesSeeder for you:
```php artisan make:seeder RolesTableSeeder```
Inside this RolesTableSeeder, we create our basic roles:
<pre>
DB::table(‘roles’)->insert([
 [‘name’ => ‘admin’],
 [‘name’ => ‘operator’],
 [‘name’ => ‘customer’],
]);
</pre>
You can add as many roles as you need. Also, you can create new roles from your website whenever you need a new one.
<hr>
The second step is to create an authorization list for each role. we create another Laravel seeder in which populate permissions table:
```php artisan make:seeder PermissionTableSeeder```
Firstly, we get all routes list. Then, We check up with the database if the permission already stored. After that, if this permission is not in the table already, we insert new permissions in the permissions table. After all, we attach all permissions to the admin role.
<pre>
$permission_ids = []; // an empty array of stored permission IDs
// iterate though all routes
foreach (Route::getRoutes()->getRoutes() as $key => $route)
{
 // get route action
 $action = $route->getActionname();
// separating controller and method
 $_action = explode(‘@’,$action);
 
 $controller = $_action[0];
 $method = end($_action);
 
 // check if this permission is already exists
 $permission_check = Permission::where(
         [‘controller’=>$controller,’method’=>$method]
     )->first();
 if(!$permission_check){
   $permission = new Permission;
   $permission->controller = $controller;
   $permission->method = $method;
   $permission->save();
   // add stored permission id in array
   $permission_ids[] = $permission->id;
 }
}
// find admin role.
$admin_role = Role::where(‘name’,’admin’)->first();
// atache all permissions to admin role
$admin_role->permissions()->attach($permission_ids);
</pre>
### LARAVEL AUTHORIZATION USING MIDDLEWARE
Every request in Laravel goes through middleware. Knowing that creating RolesAuth middleware will do Laravel authorization. You can create the middleware manually or by an artisan command:
```php artisan make:middleware RolesAuth```
Inside this middleware, we get all permissions for logged in user. Then, we check if the requested action is in the permissions list. If requested action can’t be found in permissions list, a 403 error response returns.
<pre>
// get user role permissions
$role = Role::findOrFail(auth()->user()->role_id);
$permissions = $role->permissions;
// get requested action
$actionName = class_basename($request->route()->getActionname());
// check if requested action is in permissions list
foreach ($permissions as $permission)
{
 $_namespaces_chunks = explode(‘\\’, $permission->controller);
 $controller = end($_namespaces_chunks);
 if ($actionName == $controller . ‘@’ . $permission->method)
 {
   // authorized request
   return $next($request);
 }
}
// none authorized request
return response(‘Unauthorized Action’, 403);
</pre>
Finally, you can register this middleware in Laravel and use it according to your requirements.