Laravel 11 Breeze Multi Auth Tutorial

By Hardik Savani September 4, 2024 Category : Laravel

In this tutorial, I will show you how to create multiple authentication with breeze in Laravel 11 application.

In this example, we will install a fresh Laravel 11 application for multi-auth. Then we will install Laravel Breeze for auth scaffold. Then we will add a "type" column in the users' table, where we will define three types (User, Agent, and Admin) of users. Then, we will create a "role" middleware to check access permission. So, let's see the steps below to create a full example for multi-auth.

laravel 11 multi auth

Step for Laravel 11 Breeze Multiple Authentication Example

  • Step 1: Install Laravel 11
  • Step 2: Install Laravel Breeze
  • Step 3: Create Migration and Update Model
  • Step 4: Create UserAccess Middleware
  • Step 5: Create Routes
  • Step 6: Update Controller
  • Step 7: Create Blade Files
  • Step 8: Update LoginController File
  • Step 9: Create User Seeder
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install Laravel Breeze

Now, in this step, we will create an auth scaffold command to generate login, register, and dashboard functionalities using breeze. So, run the following commands:

Laravel 11 Breeze Package:

composer require laravel/breeze --dev

Generate Auth:

php artisan breeze:install

npm install

npm run build

Step 3: Create Migration and Update Model

In this step, we need to add a new column "type" in the users table and model. Then, we need to run migration. So let's change that in both files.

Let's create a new migration using the following command:

php artisan make:migration add_type_to_users_table

next, let's update the migration:

database/migrations/2024_04_05_143013_add_type_to_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::table('users', function (Blueprint $table) {
            $table->enum('role',['admin','agent','user'])->default('user');
        });
    }
  
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
};

Now we need to run migration.

So let's run the below command:

php artisan migrate

Let's update the User Model as the code below:

app/Models/User.php

<?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',
        'role'
    ];

    /**
     * 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',
        ];
    }
}

Step 4: Create Role Middleware

In this step, we need to create a user access middleware that will restrict users from accessing that page. So, let's create and update the code.

php artisan make:middleware Role

app/Http/Middleware/Role.php

<?php

namespace App\Http\Middleware;

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

class Role
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, $role): Response
    {
        if ($request->user()->role != $role) {
            return redirect('dashboard');
        }

        return $next($request);
    }
}

Next, we need to register the Role middleware to the 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([
            'role' => \App\Http\Middleware\Role::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Step 5: Create Routes

Here, We will add following routes group where you can create new routes for users, admins and manager access. let's update code:

routes/web.php

<?php

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

use App\Http\Controllers\AdminController;
use App\Http\Controllers\AgentController;

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

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

Route::middleware(['auth', 'role:admin'])->group(function(){
    Route::get('/admin/dashboard', [AdminController::class, 'dashboard'])->name('admin.dashboard');
});

Route::middleware(['auth', 'role:agent'])->group(function(){
    Route::get('/agent/dashboard', [AgentController::class, 'dashboard'])->name('agent.dashboard');
});

require __DIR__.'/auth.php';

Step 6: Update Controller

Here, we will create new AdminController and AgentController, then update both controller file. So let's add them as follows:

first, run the following commands to create controller file:

php artisan make:controller AdminController

php artisan make:controller AgentController

app/Http/Controllers/AdminController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function dashboard()
    {
        return view('admin.dashboard');
    }
}

app/Http/Controllers/AgentController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AgentController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function dashboard()
    {
        return view('agent.dashboard');
    }
}

Step 7: Create Blade Files

In this step, we need to create a new blade file for the admin and update the blade files. So let's change it.

resources/views/admin/dashboard.blade.php

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    You are admin!.
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

resources/views/agent/dashboard.blade.php

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    You are agent!.
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

Step 8: Update AuthenticatedSessionController File

In this step, we will make changes on the AuthenticatedSessionController. When the user logs in, we will redirect them according to their access level. we will just update store() in this controller file.

app/Http/Controllers/Auth/AuthenticatedSessionController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();

        $url = "dashboard";

        if ($request->user()->role == "admin") {
            $url = "admin/dashboard";
        } else if($request->user()->role == "agent"){
            $url = "agent/dashboard";
        }

        return redirect()->intended($url);
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}

Step 9: Create User Seeder

We will create a seeder to create new admin, agent and user. So let's create the seeder using the following command:

php artisan make:seeder UserSeeder

database/seeders/UserSeeder.php

<?php

namespace Database\Seeders;

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

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        User::create([
            'name' => 'Admin',
            'email' => 'admin@gmail.com',
            'password' => Hash::make('123456'),
            'role' => 'admin'
        ]);

        User::create([
            'name' => 'Agent',
            'email' => 'agent@gmail.com',
            'password' => Hash::make('123456'),
            'role' => 'agent'
        ]);

        User::create([
            'name' => 'User',
            'email' => 'user@gmail.com',
            'password' => Hash::make('123456'),
            'role' => 'user'
        ]);
    }
}

Now let's run seeder:

php artisan db:seed --class=UserSeeder

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/

Now, Let's login with following credentials:

Normal User:

Email: user@gmail.com
Password: 123456

Admin User:

Email: admin@gmail.com
Password: 123456

Agent User:

Email: agent@gmail.com
Password: 123456

Output:

I hope it can help you...

Shares