Roles Authentication in Laravel

Dikshant Rajput
4 min readJul 10, 2021

--

Authentication is the most important part of any application and the first basic thing that separates your privileged users from a non privileged user.

In my previous blogs, I have covered these topics “Laravel Authentication(Theory & Practical Implementation)”, “Verify Users”, etc. Today, I will be writing about roles in Laravel and how can you differ your users and have separate access for them. If you haven’t read my previous blogs, I would recommend you to first read them because I will be taking the code from these blogs further and will not going to cover the basics again. So, let’s start…

I will be creating three access areas or three types of roles i.e user role, admin role and super admin role.

Database Structure

First of all we will require a table to store the three roles and have a connection between roles and users table that will be having many-to-many relationship.

php artisan make:migration create_roles_table //Roles migration filepublic function up(){Schema::create('roles', function (Blueprint $table) {    $table->id();    $table->string('name');    $table->string('slug');    $table->string('desc');    $table->timestamps();    });}

This will create a roles table with columns id, name, slug, desc where the column names are self explanatory. Then run,

php artisan make:migration create_role_user_table//Role User Pivot table migration filepublic function up(){Schema::create('role_user', function (Blueprint $table) {    $table->id();    $table->foreignId('role_id')->constrained()->onUpdate('cascade')->onDelete('cascade');    $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');    $table->timestamps();    });}

This will create a role_user pivot table with column id, role_id, user_id for defining which user have which roles.

Now run the migrations

php artisan migrate

Models

Create models for role and role_user table. Run

php artisan make:model Rolephp artisan make:model RoleUser

Role Model will look something like this with fillable array.

class Role extends Model{    use HasFactory;    protected $fillable = [        'name',        'slug',        'desc'    ];}

RoleUser Model will look something like this with fillable array.

class RoleUser extends Model{    use HasFactory;    protected $table = 'role_user';    protected $fillable = [        'role_id',        'user_id'    ];}

Seeders

We have to make three roles for which we have to seed some data or create some records in roles table, you can create record manually in db or make seeders.

php artisan make:seeder RolesSeedeerpublic function run(){    Role::insert([        [             'name'=>'Super Admin Role',             'slug'=>'SUPER_ADMIN',             'desc'=>'Access to admin section',       ],       [             'name'=>'Admin Role',             'slug'=>'ADMIN',             'desc'=>'Access to admin section',        ],        [            'name'=>'User Role',            'slug'=>'USER',            'desc'=>'User role with access to user section',        ],    ]);}

Now run,

php artisan db:seed --class=RolesSeeder

This will create some entry for roles table with roles — User role, admin role and super admin role.

We also have to create users entries in db along with role_user table entries.

php artisan make:seeder UsersSeederpublic function run(){    User::insert([     [            'name'=>'User 1',            'email'=>'user1@gmail.com',            'password'=>Hash::make('aaaaaaaa'),            'email_verified_at'=>now(),            'mobile'=>'1111111111'     ],     [            'name'=>'User 2',            'email'=>'user2@gmail.com',            'password'=>Hash::make('bbbbbbbb'),            'email_verified_at'=>now(),            'mobile'=>'1111111111'     ],     [             'name'=>'User 3',             'email'=>'user3@gmail.com',             'password'=>Hash::make('cccccccc'),             'email_verified_at'=>now(),             'mobile'=>'1111111111'        ],    ]);}php artisan make:seeder RoleUserSeederpublic function run(){      RoleUser::insert([     [          'role_id'=>1,          'user_id'=>1      ],      [          'role_id'=>2,          'user_id'=>2      ],      [           'role_id'=>3,           'user_id'=>3       ]    ]);}

Now seed them one by one in the db

php artisan db:seed --class=UsersSeederphp artisan db:seed --class=RoleUserSeeder

Now everything is ready, we just need to restrict the non-privileged user from privileged section i.e admin panel and for this we will be creating middlewares and protecting our routes.

Relationship

In User model, we have to define roles relation like this:

public function roles(){    return $this->belongsToMany(Role::class);}

Now, I will be creating some functions in the same model for checking roles of the user by passing parameters for roles slug like this :

public function hasRole($role){    return $this->roles->where('slug',$role)->count() > 0;}
public function hasAnyRole($roles){ foreach($roles as $role){ if($this->hasRole($role)){ return true; } } return false;}

The functions are self explanatory.

Middleware

We will be needing a middleware to check the requests and if the user is allowed to goo further or not. If the user doesn’t have required permission, we will be showing forbidden page.

php artisan make:middleware RoleMiddleware
public
function handle(Request $request, Closure $next, ...$roles)
{ if(!auth()->user()->hasAnyRole($roles)){ abort(403); } return $next($request);}

Now register the middleware in the App\Http\Kernel.php file in “routeMiddleware” method like this :

'role' => App\Http\Middleware\RoleMiddleware::class,

Routes

Just a last step, we need to create route and protect them using middlewares like this :

Route::group(['middleware'=>'role:ADMIN,SUPER_ADMIN'],function(){    Route::get('/admin/dashboard',function(){        return '<h1>Admin Panel</h1>';    });});

Now, if any user that doesn’t have permission of ADMIN or SUPER_ADMIN can’t visit the admin/dashboard.

You can create multiple views and areas for different type of users.

All the code related to this blog is in this repository :

I hope you like this blog and if you do, please hit that clap icon and if you have any issue or any suggestion please feel free to comment. Follow me for more such blogs.

--

--