Following the previous article, I wrote on how to handle multiple role-based authentications in Laravel which shows user role-based authentications even if you have multiple user roles without using any library.
In this article, I am going to explain how to properly handle multiple role-based authentications in the current version of Laravel and how to handle it efficiently.
We are going to use the scenario from this article, where we have 3 users with different roles and different dashboards to redirect to on successful login.
By the way, if you’re just STARTING out with Laravel, I have created a Complete Laravel Guide just for you.
The users are as follows:
- Player
- scout
- admin
Alright, if the scenario is clear enough and it’s what you’re looking for, then let’s delve into the tutorial.
Before we delve in, if you’re a backend developer or looking at delving into this career path, join other developers to receive daily articles on backend development that will boost your productivity.
Getting Started
Let’s begin by setting up our Laravel projects and installing the necessary libraries needed to handle Laravel role-based authentications.
We will start by installing a fresh new Laravel project to demonstrate, but you can skip this process if you already have your project.
The following command can be used to install a fresh Laravel project, or you can check the documentation here.
composer create-project --prefer-dist laravel/laravel MultiAuth
Setting Databases
Next, let’s set up our database and configure our .env
file to connect to our database properly.
You can create your database with any Database client of your choice and click here to see how to configure your database properly.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DB NAME HERE
DB_USERNAME=DB USERNAME HERE
DB_PASSWORD=DB PASSWORD HERE
Now, let’s set up our Eloquent database schemas.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('role');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
After setting up everything, and creating your schema as shown above.
Run the following command:
php artisan migrate
Setting up Authentication
We will move further to set up our Laravel Auth, this will create a complete user registration and login system for our new project.
Firstly, we will install Laravel Breeze package to scaffold the Auth system.
composer require laravel/breeze --dev
To generate the UI, run the following command:
php artisan breeze:install
npm run install
npm run dev
Next, navigate to /register
or /login
to make sure everything is set up properly. All Laravel Breeze configurations can be found at config/auth.php
.
Create the Middleware
Next, we will create different middleware for the different users and register them in the kernel.php
file.
php artisan make:middleware Admin
php artisan make:middleware Player
// Repeat for all users
Setting up the middleware
Now add the following codes in each of the middleware and allow the next method only on the role that equals the middleware.
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
class Player
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::check()) {
return redirect()->route('login');
}
if (Auth::user()->role == 'scout') {
return redirect()->route('scout');
}
if (Auth::user()->role == 'player') {
return $next($request);
}
if (Auth::user()->role == 'admin') {
return redirect()->route('admin');
}
}
}
In the Player
middleware above, when the role is equal to the player
we use the return the $next
method else we redirect to the other routes.
Now, let’s register the different middleware we have created above.
<?php
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
.............
'player' => \App\Http\Middleware\Player::class,
'admin' => \App\Http\Middleware\Admin::class,
'scout' => \App\Http\Middleware\Scout::class
];
Create routes:
After registering the routes, goto web.php
and add the following codes to map the routes to appropriate middleware.
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|----------------------------------------------------------
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/player', 'PlayerController@index')->name('player')->middleware('player');
Route::get('/admin', 'AdminController@index')->name('admin')->middleware('admin');
Route::get('/scout', 'ScoutController@index')->name('scout')->middleware('scout');
...........
Update Login Controller
Next, we will update the login controller and add the following lines of code to redirect to the appropriate route when a user successfully logged in.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo;
public function redirectTo()
{
switch(Auth::user()->role){
case 'admin':
$this->redirectTo = '/admin';
return $this->redirectTo;
break;
case 'player':
$this->redirectTo = '/player';
return $this->redirectTo;
break;
case 'scout':
$this->redirectTo = '/scout';
return $this->redirectTo;
break;
default:
$this->redirectTo = '/login';
return $this->redirectTo;
}
// return $next($request);
}
}
Set up the Views
Lastly, let’s set up the different landing pages for each dashboard to display the different users.
<?php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif
You are in ADMIN Dashboard!
</div>
</div>
</div>
</div>
</div>
@endsection
The code above shows only a demo of Admin
dashboard, you can create as many dashboards as possible and add the route in the web.php
file with appropriate middleware created for it.
Conclusion
I 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, let’s hear it in the comment section below and we will update this post accordingly.
You can get the full source code here
Thank you for reading my article.
Here at my blog or medium I regularly write about backend development, digital marketing, and content management system.