Laravel 11 Multiple Authentication Tutorial

Multiple authentication in Laravel 11 refers to the ability to authenticate different types of users within the same application with different types of users accessing different parts of your application with their auth credentials and access levels.

Let’s start building a multiple authentication system using Bootstrap UI:

Step 1: Download Laravel 11

Run composer command to download and setup laravel 11:

composer create-project laravel/laravel MultiAuth

Step 2: Initialize Database

Edit .env file from root folder of laravel project and configure database, something like this:

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Step 3: Add a Field in the Table using Migration

Run the following command to create a migration file to add field in database table:

php artisan make:migration add_to_users_table

Edit add_to_users_table.php file from database/migrations/ folder and add field in it; something like this:

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

Run migration command to create tables in database:

php artisan migrate

Now Edit DatabaseSeeder.php file from database/seeders/ folder and add the following method into it:

    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 the following command to add user and admin into a database table:

php artisan db:seed --class=DatabaseSeeder

Step 4: Edit User Model

Edit user.php model from app/Models folder, and add the following code in it:

<?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 5: Setup Bootstrap UI Auth

Install laravel UI and generate auth template and controllers by running the following commands:

For laravel UI:

composer require laravel/ui 

For Bootstrap Auth:

php artisan ui bootstrap --auth 
npm install
npm run build

Step 6: Create Middleware for Auth Access Level

Run the make middleware command to create a middleware file:

php artisan make:middleware AccessLevel

Edit AccessLevel.php file from app/Http/Middleware/ folder and write a logic in it to handle HTTP requests by user access level:

<?php

namespace App\Http\Middleware;

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

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

Next register AccessLevel middleware in bootstrap/app.php file; something like this:

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

Step 7: Define Routes and use Middleware

Edit web.php file form routes folder and define routes for different type of user level and add middleware in it; something like this:

<?php

use Illuminate\Support\Facades\Route;

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

Auth::routes();


//users routes
Route::middleware(['auth', 'access-level:user'])->group(function () {

Route::get('/welocme', [App\Http\Controllers\HomeController::class, 'index'])->name('welcome');
});

// admin routes
Route::middleware(['auth', 'access-level:admin'])->group(function () {

Route::get('/admin/dashboard', [App\Http\Controllers\HomeController::class, 'dashboard'])->name('admin.dashboard');
});

Step 8: Add Methods in Controller

Edit HomeController.php controller file from app/Http/Controllers/ folder and add some methods into it, something like this:

<?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('home');
}

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

}

Step 9: Create Blade View Files

Go to resources/views/ folder, create dashboard.blade.php and home.blade.php file for user and admin page:

Add code in 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

Add code in home.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 10: Edit Authentication Controller File

Edit LoginController.php file from app/Http/Controllers/Auth/ folder, and add code in redirect user according to their access level:

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

}
}

Step 11: Test Application

Run the following command to start application server:

php artisan serve

Hit http://localhost:8000/ url on browser for testing:

This tutorial has taught you how to create a multiple authentication system in a Laravel 11 application using laravel UI and bootstrap auth.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *