Multiple Role Base Access in Laravel 8

Building secure applications

Nifla Fareed
LinkIT
2 min readMay 19, 2021

--

Image by Clker-Free-Vector-Images from Pixabay

In this article, I would like to show you how to demonstrate role base access in Laravel if you have multiple roles in your project or application. By following the below steps you can redirect users to their dashboard according to their roles.

Create A Laravel Project

You should run the below command to create a new Laravel project.

Make sure you have already installed Laravel on your PC.

Check Laravel Installation

Set up your .env file

Create a new database in phpMyAdmin and enter your database name and password in the .env file.

Set up your database

Next step you should customize your database tables before migrating them. Goto the user migration file under the migrations folder add another attribute called roles.

Here I have made the role attribute nullable to avoid exception errors.

After setting up your database run the below command to migrate your database.

Set up Authentication

Laravel provides the tools to implement authentication easily. Therefore to set up user registration and login system run the below commands.

After setting up registration and login run the below command.

After running the above command, type 127.0.0.1:8000 or localhost:8000 in the browser. You can now register different users to the system through the registration link or add dummy data to the database manually.

In this project, I have used three different roles as follows.

  1. Admin
  2. Academic
  3. Student

Create controllers

Create controllers for each role in your project.

Run the below command to create controllers

The controller should return the blade file of each role inside the index function.

Create Middleware

Create middleware files for each role.

run:

Edit each middleware file. Here I have assigned each role’s middleware to its respective routes.

After editing each middleware file register them in the Kernel.php file under the route middleware array.

Create Dashboard Views

Create dashboard view files for each role as required, inside the views folder in your project.

Once you finished creating view files, set up routes for each view file inside the web.php file. (inside routes folder in your project).

Edit Login Controller

When users log in to the system you should redirect them to the correct dashboard according to the user’s role.

You can do this in the RegisterController also if required. So that user will be redirected to the dashboard based on his/her role once the user is registered to the system.

Hope this article helps to implement Laravel role base access if you have different types of roles in your system.

Thank you for reading!

--

--

Nifla Fareed
LinkIT

Software Engineer @ IFS | Graduated from University of Moratuwa, Sri Lanka