Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Multi Authentication Tutorial

Last Updated on May 20, 2024 by

Multi authentication (or multi-auth) in Laravel 11 project allows different types of users to log in and access their respective routes in application.

Let’s make multi auth using Bootstrap Auth UI:

Step 1 – Set Up Laravel 11 Project

To create a new Laravel project using Composer command:

composer create-project --prefer-dist laravel/laravel multi-user-authentication

Step 2 – Set up Database

Add database details for multi auth in .env file:

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=database
DB_USERNAME=database user
DB_PASSWORD=user password

Step 3 – Add type in Users Table

Create migration file for add user type in database:

php artisan make:migration add_type_of_user_table

Add the following function in database/migrations/add_type_of_user_table.php file:

public function up(): void
{
    Schema::table('users', function (Blueprint $table) {
        $table->tinyInteger('type')->default(1); // 1 = User, 2 = Admin
    });
}

Create tables in database by using the migration command:

php artisan migrate

Step 4 – Add Users in Database

Add the following method into database/seeders/DatabaseSeeder.php file to add users in database:

 public function run(): void
    {
        $users = [
            [
               'name'=>'Admin User',
               'email'=>'[email protected]',
               'type'=>2,
               'password'=> bcrypt('123456'),
            ],
            [
               'name'=>'User',
               'email'=>'[email protected]',
               'type'=>1,
               'password'=> bcrypt('123456'),
            ],
        ];
    
        foreach ($users as $key => $user) {
            User::create($user);
        }
    }

Run seeder to add users in database:

php artisan db:seed --class=DatabaseSeeder

Step 5 – Install Bootstrap UI Auth Package

To install the Bootstrap UI package for Laravel to scaffold the authentication views:

composer require laravel/ui
php artisan ui bootstrap --auth 
npm install
npm run build

Step 6 – Create Middleware for Authentication

To create middleware for authentication by running the following command:

php artisan make:middleware GrantByUser

To implement code in app/Http/Middleware/GrantByUser.php file to handle HTTP requests:

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class GrantByUser
{
    /**
     * 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.']);
    }
}

Define GrantByUser.php middleware in bootstrap/app.php file:

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

Step 7 – Add middleware to routes

Add grantByUser middleware on routes to access views according to user level:

<?php

use Illuminate\Support\Facades\Route;

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

Auth::routes();


//users routes
Route::middleware(['auth', 'grant-by-user:user'])->group(function () {
  
    Route::get('/user/dashboard', [App\Http\Controllers\HomeController::class, 'index'])->name('user.dashboard');
});
  
// admin routes
Route::middleware(['auth', 'grant-by-user:admin'])->group(function () {
  
    Route::get('/admin/dashboard', [App\Http\Controllers\HomeController::class, 'dashboard'])->name('admin.dashboard');
});

Step 8 – Define Access Level Methods in the Controller

Define some methods in the App/Http/Controllers/HomeController.php file for the user access level:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;

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(): View
    {
        return view('user_dashboard');
    } 
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function dashboard(): View
    {
        return view('admin_dashboard');
    }
  
}

Modify Auth login method in app/Http/Controllers/Auth/LoginController.php file:

<?php

namespace App\Http\Controllers\Auth;

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

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): RedirectResponse
{   
    $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{
            return redirect()->route('user.dashboard');
        }
    }else{
        return redirect()->route('login')
            ->with('error','Email-Address And Password Are Wrong.');
    }
      
}
}

Step 9 – Add Method in User.php Model

Add some method in app/Models/user.php file:

<?php
  
namespace App\Models;
  
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
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'type'
    ];

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

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

    /**
     * Interact with the user's first name.
     *
     * @param  string  $value
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
protected function type(): Attribute
{
    return new Attribute(
        get: fn ($value) =>  $value == 2 ? "admin" : "user",
    );
}

}

Step 10 – Create Views for Multi Auth

Create views for each type of user in resources/views folder.

For admin, resources/views/admin_dashboard.blade.php file:

@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
 
                    <h2>You are a Admin User.</h2>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

For user, resources/views/user_dashboard.blade.php file:

@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
 
                    <h2>You are a User.</h2>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 11 – Test Application

For test this application, run the following command:

php artisan serve

Hit http://127.0.0.1:8000/ url on browser for testing.

In this Laravel 11 Multi Auth Bootstrap UI tutorial, I have shown you how to make multi authentication system for different types of users like admin, user etc.

Leave a Comment