How to Create Multiple Authentication in Laravel 11

Hello developers, In this guide we'll see how to create multiple authentications in laravel 11. Here, we'll learn about how to create multiple authentications with the help of middleware in laravel 11. Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.

Laravel includes a middleware that verifies whether the user of your application is authenticated. If the user is not authenticated, the middleware will redirect them to your application's login screen.

We will add three types of users:

1. User

2. Manager

3. Super Admin

Laravel 11 Multiple Authentication using Middleware

laravel 11 multiple authentication using middleware

 

Step 1: Install Laravel 11

In this step, we'll install the laravel 11 application using the following composer command.

composer create-project laravel/laravel laravel-11-multi-auth

 

Step 2: Database Configuration

Now, we will configure a database in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_11_multi_auth
DB_USERNAME=root
DB_PASSWORD=

 

Step 3: Migration and Model

Then, we will add the "type" column in the user's table and model.

database/migrations/create_users_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->tinyInteger('type')->default(0); /* Users: 0=>User, 1=>Super Admin, 2=>Manager */
            $table->rememberToken();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

Now, run the migration using the below command.

php artisan migrate

After that, we will update the User model.

app/Models/User.php

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;
  
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
      
    protected $fillable = [
        'name',
        'email',
        'password',
        'type'
    ];
  
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     
    protected function type(): Attribute
    {
        return new Attribute(
            get: fn ($value) =>  ["user", "super-admin", "manager"][$value],
        );
    }
}

 

Step 4: Create Auth using scaffold

In this step, we will create authentication using the scaffold to create a login, register, and dashboard.

Laravel UI Package:

composer require laravel/ui

Create Auth:

php artisan ui bootstrap --auth
npm install & npm run dev

 

Step 5: Create Middleware

Now, we will create AuthUser middleware that will restrict users from accessing other pages.

php artisan make:middleware AuthUser

app/Http/middleware/AuthUser.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
  
class AuthUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, $userType): Response
    {
        if(auth()->user()->type == $userType){
            return $next($request);
        }

        return response()->json(['You do not have permission to access for this page.']);
    }
}

 

Step 6: Register Middleware

In this step, we will register AuthUser middleware in the app.php file, as illustrated in the code snippet below:

bootstrap/app.php

<?php
   
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
   
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'authUser' => \App\Http\Middleware\AuthUser::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

 

Step 7: Create Routes

Then, we'll create a route with middleware and user types like manager and super-admin.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;  
use App\Http\Controllers\HomeController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();
  

// Users Routes
Route::middleware(['auth', 'authUser:user'])->group(function () {
    Route::get('/dashboard', [HomeController::class, 'index'])->name('dashboard');
});

// Manager Routes
Route::middleware(['auth', 'authUser:manager'])->group(function () {  
    Route::get('/manager/dashboard', [HomeController::class, 'managerDashboard'])->name('manager.dashboard');
});  

// Super Admin Routes
Route::middleware(['auth', 'authUser:super-admin'])->group(function () {
    Route::get('/admin/dashboard', [HomeController::class, 'adminDashboard'])->name('admin.dashboard');
});

 

Step 8: Update the Controller

Now, we will add methods in the HomeController.php file.

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class HomeController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('home');
    }

    public function managerDashboard()
    {
        return view('manager_dashboard');
    }

    public function adminDashboard()
    {
        return view('super_admin_dashboard');
    }
}

 

Step 9: Create a Blade file

In this step, we will create a blade file for the manager and super-admin.

resources/views/home.blade.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 login as a user role.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

resources/views/manager_dashboard.blade.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">
                    You are login as a manager role.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

resources/views/super_admin_dashboard.blade.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">
                     You are login as a super admin role
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Step 10: Update LoginController

In this step, we will update the LoginController file so update the following code to that file.

app/Http/Controllers/Auth/LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function login(Request $request)
    {   
        $input = $request->all();
     
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
     
        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
        {
            if (auth()->user()->type == 'super-admin') {
                return redirect()->route('admin.dashboard');
            }else if (auth()->user()->type == 'manager') {
                return redirect()->route('manager.dashboard');
            }else{
                return redirect()->route('dashboard');
            }
        }else{
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }
          
    }
}

 

Step 11: Create Seeder

Now, we will create a seeder for the super admin and user.

php artisan make:seeder CreateUsersSeeder

Database/Seeders/CreateUsersSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;

class CreateUsersSeeder extends Seeder
{
    public function run()
    {
        $users = [
            [
               'name'=>'User',
               'email'=>'user@techsolutionstuff.com',
               'type'=>0,
               'password'=> bcrypt('123456'),
            ],
            [
               'name'=>'Super Admin',
               'email'=>'super-admin@techsolutionstuff.com',
               'type'=>1,
               'password'=> bcrypt('123456'),
            ],
            [
               'name'=>'Manager',
               'email'=>'manager@techsolutionstuff.com',
               'type'=> 2,
               'password'=> bcrypt('123456'),
            ],
        ];
    
        foreach ($users as $key => $user) {
            User::create($user);
        }
    }
}

Now, run seeder using the below command:

php artisan db:seed --class=CreateUsersSeeder

After that, run the laravel 11 application using the following command.

php artisan serve

Now, open the browser add the given URL, and check the created role using the email and password.

http://localhost:8000/login

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS