Configuration of Custom Roles Using Middleware

Learn how to create and manage multiple roles via middleware in Laravel.


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:

  1. 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.

  2. In the up() function of the roles migration, we insert three different roles into the roles table.

  3. To assign users a role, we add a foreign key to the user table. To add a foreign key, we create a new migration named add_fk_to_users.

  4. To manage role-based access, we create middleware named studentMiddleware and register it in kernel.php. In this middleware, we check the user login status (Auth::check) and then fetch the user role and apply a constraint to it.

  5. 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 1200+ tech skills courses.