Configuration of Custom Roles Using Middleware
Learn how to create and manage multiple roles via middleware in Laravel.
We'll cover the following
Introduction
A system can contain a wide variety of user types. Depending on the exact roles that each user plays, their access to certain functionalities might change. For instance, in a school information management system, three main types of stakeholders—students, teachers, and administration—play vital roles.
Every role needs to be limited within its specific boundaries. To configure role management, Laravel provides a convenient way to use middleware
and sessions
.
After considering the specific needs of a school management system, the following steps can be adopted to manage access to different roles:
We create a roles table using
php artisan make:migration create_roles_table
. The table migration contains two tables, one for storing role names and the other for storing role descriptions.In the
up()
function of the roles migration, we insert three different roles into the roles table.To assign users a role, we add a
foreign key
to the user table. To add aforeign key
, we create a new migration namedadd_fk_to_users
.To manage role-based access, we create middleware named
studentMiddleware
and register it inkernel.php
. In this middleware, we check the user login status (Auth::check
) and then fetch the user role and apply a constraint to it.We add a dashboard view with three buttons, each representing a role. Upon clicking the button named “student,” a route is triggered onto which the
studentAuthenticate
middleware is applied.
Get hands-on with 1400+ tech skills courses.