Multi-Role Login and Authentication in Laravel 10
Role-based authentication is an authorization technique for Laravel applications. In this Laravel role-based authentication tutorial, we’ll learn how to set up role-based authorization in Laravel from scratch. This Laravel 8 role-based authentication example will establish separate admin panels for admin and super admin to enable role-based Laravel authorization.
In this Laravel role-based authentication tutorial, we’ll construct middleware to manage user access. Sometimes we need to establish an admin panel in Laravel by implementing role-based authentication or login systems.
Before we begin with role-based authentication and authorization in Laravel, let’s define what role-based authorization is and what we can accomplish with it.
Assume we are developing an application that will be used by a wide range of customers. However, some aspects of the application should only
Step 1 - Create Laravel Project
- Open your CMD.
- Navigate to the folder where you plan to create your Laravel project.
- Execute the following command to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel your-project-name
Replace text “your-project-name” with the desired name for your Laravel project.
Step 2 - Create Middleware
Create middleware to control user access by writing the following command:
php artisan make:middleware CheckRole
Step 3 - Create Controller
Let’s create the AdminController and SuperAdminController
php artisan make:controller AdminController
php artisan make:controller SuperAdminController
Next, create an index method
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller {
/**
* Display the admin dashboard.
*
* @return \Illuminate\View\View
*/
public function index() {
return view('admin.home');
}
}
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SuperAdminController extends Controller {
/**
* Display the admin dashboard.
*
* @return \Illuminate\View\View
*/
public function index() {
return view('superadmin.home');
}
}
The AdminController’s index method retrieves the home page from the ‘admin’ folder, while the SuperAdminController’s index method fetches the home page from the ‘super admin’ view folder.
Step 4 - Create View
Create a new folder called ‘admin’ inside the ‘resources/views’ directory. Then, add a new file named ‘home.blade.php’ to improve the organization of your Laravel project.
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Super Admin Dashboard</div>
<div class="panel-body">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
Welcome to the Admin Dashboard. Your presence here signifies special privileges!
</div>
</div>
</div>
</div>
</div>
@endsection
Afterward, establish a fresh directory named ‘superadmin’ within the ‘resources/views’ path. Subsequently, introduce a new file named ‘home.blade.php’ inside this newly created ‘superadmin’ folder.
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Super Admin Dashboard</div>
<div class="panel-body">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
Welcome to the Super Admin Dashboard. Your presence here signifies special privileges!
</div>
</div>
</div>
</div>
</div>
@endsection
Include a route entry in the ‘web.php’ file located within the ‘routes’ directory to define the desired routing for your Laravel application.
Route::get('/admin', 'AdminController@index');
Route::get('/superadmin', 'SuperAdminController@index')
Step 5 - Create Role Model and Migration
php artisan make: model Role -m
The command that follows will generate a model class for the roles table and a migrations file under database > migrations. Edit the CreateRolesTable class in the migrations folder.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('roles');
}
}
Next, we have to create a many-to-many relationship between the User and Role.
public function roles() {
return $this ->belongsToMany('App\Role')->withTimestamps();
}
Add users() to your Role.php class
public function users() {
return $this ->belongsToMany('App\User')->withTimestamps();
}
Step 6 - Create Migration for the role_user table:
We need another table, which holds the data of which role is assigned to which user.
php artisan make:migration create_role_user_table
Edit the CreateRoleUserTable class in the migrations folder:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoleUserTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
Next, we need to provide a many-to-many relationship between User and Role
Add roles() method to your User.php class
public function roles()
{
return $this
->belongsToMany('App\Role')
->withTimestamps();
}
Add users() to your Role.php class
public function users() {
return $this ->belongsToMany('App\User') ->withTimestamps();
}
Step 7 - Testing the roles and login
Run the following migrate command to create table, set the database and set in .env file.
php artisan migrate
You can register new users by navigating to the /register url. Once you have added a few users, you can give roles to them in the role_user database.
Step 8 - Update the following
Open user.php and add these small methods that will be used to verify if the user has a specific position or roles.
public function authorizeRoles($roles) {
if ($this->hasAnyRole($roles)) {
return true;
}
abort(401, 'This action is unauthorized.');
}
public function hasAnyRole($roles)
{
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
}
else {
if ($this->hasRole($roles)) {
return true;
}
}
return false;
}
public function hasRole($role) {
if ($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
With each of these methods, you can use the hasRole method to verify only against a single role. Alternatively, you can check for several roles by sending an array to the authorizeRoles function. For the time being, we will utilize the hasRole method to compare against a single role. Let us proceed to construct the Middleware for the same.
Step 9 - Create CheckRole Middleware
Create CheckRole middleware with the following command.
php artisan make:middleware CheckRole
Update middleware with the following:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $role) {
if (! $request->user()->hasRole($role)) {
abort(401, 'This action is unauthorized.');
} return $next($request);
}
}
The next step is to register the middleware that we just constructed. Open Kernal.php, which is located under App >, and change the array $routeMiddleware to add the role middleware.
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'role' => \App\Http\Middleware\CheckRole::class,
];
Step 10 - Update Controller
Open AdminController.php. The code below in the constructor method checks if the logged-in user has the ROLE_ADMIN role assigned to them.
public function __construct() {
$this->middleware('auth');
$this->middleware('role:ROLE_ADMIN');
}
public function __construct() {
$this->middleware('auth');
$this->middleware('role:ROLE_SUPERADMIN');
}
Some aspects of your program are only accessible to VIP users. So far, there has been an excessive amount of code and reading. That section of the software is now only accessible to privileged users. This means you will have complete control over which users have how much access to a Laravel-based application. Looking for Laravel app development services? Need to enhance your existing Laravel application? If you need assistance with the Laravel application, call Avya Tech, a reputable Laravel web development firm.