798 views
asked in Laravel by
Laravel 11 Multiple Authentication Using Middleware

1 Answer

answered by

Laravel 11 Multiple Authentication Using Middleware

Laravel 11 multi auth creates a middleware for checking the user type. It is a user, admin and super admin. And create middleware and configure it in the app.php file.

In this example, we will add three types of users:

1. User

2. Admin

3. Super Admin

When we log in as an user then it will redirect to related user routes. If you log in as super admin and admin then it will redirect to super admin and admin routes respectively.

Step 1: Install Laravel 11

In this step, we will install the laravel 11 application using the below command.

composer create-project --prefer-dist laravel/laravel MultiAuthLaravel_11
cd MultiAuthLaravel_11

Open your project in any text editor like vscode, sublime, notepad++ etc.

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=MultiAuthLaravel_11
DB_USERNAME=root
DB_PASSWORD=

Step 3: Update Migration and Model

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

//database/migrations/0001_01_01_000000_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.
     */
    public function up(): void
    {
        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); /* 0-user, 1- admin, 2- super-admin */
            $table->rememberToken();
            $table->timestamps();
        });

        Schema::create('password_reset_tokens', function (Blueprint $table) {
            $table->string('email')->primary();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });

        Schema::create('sessions', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->foreignId('user_id')->nullable()->index();
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->longText('payload');
            $table->integer('last_activity')->index();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
        Schema::dropIfExists('password_reset_tokens');
        Schema::dropIfExists('sessions');
    }
};

At this juncture, execute the migration by using the following 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 Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'type',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    protected function type(): Attribute
    {
        return new Attribute(
            get: fn ($value) => ["user", "admin", "super-admin"][$value],
        );
    }
}

Step 4: Create Auth using scaffold

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 MultiAuthUser Middleware

Now, we will create MultiAuthUser middleware that will restrict users to access other pages.

php artisan make:middleware MultiAuthUser

//app/Http/middleware/MultiAuthUser.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class MultiAuthUser
{
    /**
     * 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 are not authorized to access this page.']);
    }
}

Step 6: Create Middleware alias in app.php file. 

//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([
            'user-access' => \App\Http\Middleware\MultiAuthUser::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Step 7: Create Routes

In this step, we will create a route with middleware and user types like user, admin and super-admin.

//routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// user route
Route::middleware(['auth', 'user-access:user'])->group(function () {
    Route::get('/dashboard', [HomeController::class, 'index'])->name('dashboard');
});
// admin route
Route::middleware(['auth', 'user-access:admin'])->group(function () {
    Route::get('/admin/dashboard', [HomeController::class, 'adminDashboard'])->name('admin.dashboard');
});
// super admin route
Route::middleware(['auth', 'user-access:super-admin'])->group(function () {
    Route::get('/super-admin/dashboard', [HomeController::class, 'superadminDashboard'])->name('superadmin.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
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

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

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

Step 9: Create a Blade file

In this step, we will create a blade file for the admin 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 logged in as User!') }}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

//resources/views/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">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    {{ __('You are logged in as admin!') }}
                </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">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    {{ __('You are logged in as superadmin!') }}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 10: Update LoginController

In this step, we will some changes to the LoginController.

//app/Http/Controllers/Auth/LoginController.php

<?php

namespace App\Http\Controllers\Auth;

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

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    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 == 'admin')
            {
                return redirect()->route('admin.dashboard');
            } else if(auth()->user()->type == 'super-admin') {
                return redirect()->route('superadmin.dashboard');
            } else {
                return redirect()->route('dashboard');
            }
        } else {
            return redirect()->route('login')->with('error', 'email or password is incorrect.');
        }
    }

}

Step 11: Create Seeder

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

php artisan make:seeder CreateUsersSeeder

<?php

namespace Database\Seeders;

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

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $users = [
            [
                'name' => 'User',
                'email' => 'user@chirags.in',
                'password' => Hash::make('user@chirags.in'),
                'type' => 0,
            ],
            [
                'name' => 'Admin',
                'email' => 'admin@chirags.in',
                'password' => Hash::make('admin@chirags.in'),
                'type' => 1,
            ],
            [
                'name' => 'Super Admin',
                'email' => 'superadmin@chirags.in',
                'password' => Hash::make('superadmin@chirags.in'),
                'type' => 2,
            ]
        ];
        foreach($users as $key => $user)
        {
            User::create($user);
        }
    }
}

Now, initiate the seeder by executing the following command:

php artisan db:seed --class=CreateUsersSeeder

Subsequently, launch the Laravel application.

php artisan serve

At this point, access your browser and navigate to the provided URL. Verify the assigned role by logging in with the specified email and password.

http://127.0.0.1:8000/login

Youtube Tutorial Link:

https://youtu.be/mKgmzvGXgeA

Download zip project file https://www.chirags.in/downloads/laravel/MultiAuthLaravel_11.zip

Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...