Multiple role-based authentication in Laravel
Tags: backend, auth, authentication, laravel
Published: 2019-06-19 11:25:15

---
title: Multiple role-based authentication in Laravel
published: true
tags: backend,auth,authentication,laravel
canonical_url: https://masteringbackend.com/posts/multiple-role-based-authentication-in-laravel
---

Hey guys, in this article, am going to show you how to[implement multiple role-based authentication in Laravel](https://masteringbackend.com/posts/multiple-role-based-authentication-in-laravel) even if you have many different users and multiple dashboards respectively.

Before we delve into achieving that, let me breakdown my scenarios or problems I was facing in a project I was working for a company, that made me spend almost two weeks trying to figure it out.

In this project, I was presented with six (6) different users and their respective dashboards too, the users were as follows viz:

1. Super Admin 
2. Admin 
3. Players 
4. Teams 
5. Academics 
6. Scouts

So, the problem was to redirect the users to their respective dashboards on successful logins and restrict access to any other dashboards even if they typed in the URL to or try to access the other dashboard, it should redirect them back to their default dashboard.

As I read through many blog posts, video tutorials, and questionings which was great, I discovered that whenever I successfully implement a solution, I will always discover a fault during security test/checks such as “too many redirect errors” or enabling a logged-in player to access a scout dashboard, etc.

I also discovered many solutions such as the use of guards, middleware, etc. which helped tremendously.

#### GETTING STARTED

Enough of the housekeeping things, let me move down to how I successfully implement multiple role-based authentications in Laravel and save myself two weeks of sleepless nights.

We will start by installing a fresh new Laravel project, you can skip these steps if you are comfortable with it.

#### **CREATING A FRESH LARAVEL**

Type in the following commands in your projects folder assuming you have php 7.\* and composer installed. [You can check here to learn how to install Laravel.](https://laravel.com/docs/)

`composer create-project --prefer-dist laravel/laravel MultiAuth`

#### S **ETTING UP YOUR DATABASE AND .ENV FILE**

The next step is to set up your database migrations and configuring your environment file. Go to your phpMyAdmin and create a database.

Open your user migration file and add the following columns


{% gist
https://gist.github.com/Kaperskyguru/84e263effabde14173539f5404661ca4
%}

After that, open your .env file and pass in your database credentials

Run your migrations

`php artisan migrate`

You can set up database seeders to fill your database with data or you can add it manually, whichever way is good, or you can simply use my code examples since I have set up a database seeder already just for this example.

#### **SETTING UP USER AUTH.**

After setting up your database and running migrations, the next step is to use Laravel default authentication which is just fine for our example, Thanks to Laravel teams.

By just running:

`php artisan make:auth`

You should successfully set up a complete user registration and login system out of the box, now visit your newly created Laravel project by typing.

`php artisan serve`

And typing _127.0.0.1:8000_ in the browser. At this stage, you can decide to seed six (6) different users with corresponding user roles or manually insert them into the database.

So, our user role is going to be numerical as follows:

1. Super Admin 
2. Admin 
3. Player 
4. Team 
5. Academic 
6. Scout

After properly seeding the dummy user data, if you are happy with it, let's move to the next step.

#### **CREATING DASHBOARD CONTROLLERS**

The next step will be to create different dashboard controllers for different users. Type

`php artisan make:controller AdminController`

`php artisan make:controller PlayerController`

Repeat until you complete the six (6) dashboards.

#### **CREATING MIDDLEWARES**

After creating the different controllers, the next step is to create the different middleware corresponding to the different user roles. TYPE

`php artisan make:middleware Admin`

`php artisan make:middleware Player`

Repeat until you complete the six (6) middlewares.

After creating the middleware, now go into the kernel.php file under the $routeMiddleware array and register them.

{% gist
https://gist.github.com/Kaperskyguru/c7f94f262b0dc6912a8987e6d3cb5589
%}

After registering the middleware appropriately, the next step is assigning the middleware to the different controllers or routes you want to protect.

#### **SETTING UP VIEWS AND ROUTES**

Go to your views folder and create a different view dashboard. Remember the dashboard files can be inside different folders, it doesn’t matter, just route them correctly inside your controllers.

![View Folder in a laravel project](https://codelikemad.com.ng/wp-content/uploads/2019/01/viewFolder-1.png)<figcaption>Different user dashboards</figcaption>

Inside each of the dashboards, I added a dummy text, just to demonstrate.


{% gist
https://gist.github.com/Kaperskyguru/bd04cb56977835be5ceb3e785e5267fb
%}

After creating the view, go to web.php under the routes folder and set up the different routes to access the different dashboards.

{% gist
https://gist.github.com/Kaperskyguru/6e6afa952ba5751754be0952b2e371ea
%}

Now, here is the interesting part, in my example or project, I prefer assigning the middleware to the routes instead of adding it into the Controller constructors.

#### **EDITING THE MIDDLEWARE**

After registering and assigning the middleware to the routes or controllers, let edit the contents of each of the middlewares. So, inside the handle method, check if the user is Authenticated and redirect according to the user role to the different dashboards.

{% gist
https://gist.github.com/Kaperskyguru/ab6114ba9b70f92039ec3ab0e28eda82
%}

**EDITING THE LOGIN AND REGISTER CONTROLLER**

After a successful login, you need to redirect the user to the appropriate dashboard based on the user role.

{% gist
https://gist.github.com/Kaperskyguru/71ec5057797b687f27aa702d597d332a
%}

You can do the same with Register Controller or you can simply redirect users to the verify page and after verification, you can redirect to the dashboard or login page again depending on your project.

#### **CONCLUSIONS**

Wow!!! Congratulations, that was a long read and code typing, [you can watch the video here.](http://bit.ly/multimegaschool)

So far, the problem we have solved is preventing a logged-in user from accessing other users’ dashboards and also preventing “too many redirect errors” when working with guards wrongly.

we understand that there are many ways to kill a rat, we want to hear your thoughts and best practices on how to solve this same issue, if you have encountered it before, how did you solve it, lets hear it in the comment section below and we will update this post accordingly.

#### You can get the full [source code here](https://github.com/Kaperskyguru/MultiAuth)

If you enjoy this post make sure you share it with your friends and subscribe to my growing [channel](http://bit.ly/multimegaschool).

_If you are interested in backend development (or you’re internet enthusiast) both (Mobile | Web | Desktop) subscribe to my _[_Youtube channel_](http://bit.ly/multimegaschool)_, we will be posting a collection of help full tutorials and guides like this one for artisans_

The post [Multiple role-based authentication in Laravel](https://masteringbackend.com/posts/multiple-role-based-authentication-in-laravel) appeared first on [Masteringbackend](https://masteringbackend.com).