How to Create Multiple Authentication in Laravel 9 App
First we need to download the new laravel application using the following command.
composer create-project laravel/laravel laravel-multi-auth
Now, go to the project directory.
cd laravel-multi-auth
1-) Setup Database Connection
Establish a database connection, open .env file and define your database details it makes the consensus between laravel and database.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
2-) Setting up migration and model
Next, add is_admin column in the users table using mirgration file. So, Open the creates_users_table.php migration file, which is placed on Database/migration and update the following field for admin.
<?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=>Admin, 2=>Manager */
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
Next open app/User.php and update the below field name is_admin here:
<?phpnamespace 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", "admin", "manager"][$value],);}}
Now, add is_admin filed after that will use the below command for creating this field into the database.
php artisan migrate
Now, create a build-in authentication system. Use the below command for creating the default auth system in laravel. And change laravel build-in auth system to multi auth system
This command will create routes, controllers and views files for Laravel Login Authentication and registration. It means to provide a basic laravel login authentication and registration Complete system. Let’s open the command prompt and type the below command.
3-) Then install laravel 9 UI in your project using the below command:
composer require laravel/ui
Now, execute the below command on terminal for creating login, registration, forget password and reset password blade files:
php artisan ui bootstrap --auth
Then execute the following commands:
npm install
npm run dev
4-) Create UserAccess Middleware
In this step, we require to create user access middleware that will restrict users to access that page. so let’s create and update code.
php artisan make:middleware UserAccess
app/Http/middleware/UserAccess.php
<?phpnamespace App\Http\Middleware;use Closure;use Illuminate\Http\Request;class UserAccess{/*** Handle an incoming request.** @param \Illuminate\Http\Request $request* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse*/public function handle(Request $request, Closure $next, $userType){if(auth()->user()->type == $userType){return $next($request);}return response()->json(['You do not have permission to access for this page.']);/* return response()->view('errors.check-permission'); */}}
app/Http/Kernel.php
....protected $routeMiddleware = ['auth' => \App\Http\Middleware\Authenticate::class,'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,'can' => \Illuminate\Auth\Middleware\Authorize::class,'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,'user-access' => \App\Http\Middleware\UserAccess::class,];....
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
<?phpuse 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();/*--------------------------------------------------------------------------------------All Normal Users Routes List----------------------------------------------------------------------------------------*/Route::middleware(['auth', 'user-access:user'])->group(function () {Route::get('/home', [HomeController::class, 'index'])->name('home');});/*--------------------------------------------------------------------------------------All Admin Routes List----------------------------------------------------------------------------------------*/Route::middleware(['auth', 'user-access:admin'])->group(function () {Route::get('/admin/home', [HomeController::class, 'adminHome'])->name('admin.home');});/*--------------------------------------------------------------------------------------All Admin Routes List----------------------------------------------------------------------------------------*/Route::middleware(['auth', 'user-access:manager'])->group(function () {Route::get('/manager/home', [HomeController::class, 'managerHome'])->name('manager.home');});
6-) Update Controller
Here, we need add adminHome() and managerHome method for admin route in HomeController. so let’s add like as bellow:
app/Http/Controllers/HomeController.php
<?phpnamespace 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 adminHome(){return view('adminHome');}public function managerHome(){return view('managerHome');}}
7-) Configure Blade View
Open the pre-defined resources/views/home.blade.php file and insert the foundation code inside the 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('login-success'))
<div class="alert alert-success" role="alert">
{{ session('login-success') }}
</div>
@endif
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif You are normal user.
</div>
</div>
</div>
</div>
</div>
@endsection
Create and open resources/views/admin-home.blade.php file and add the code.
@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('login-success'))
<div class="alert alert-success" role="alert">
{{ session('login-success') }}
</div>
@endif
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif You are admin.
</div>
</div>
</div>
</div>
</div>
@endsection
8-) Configure Login Controller
In this step we will configure LoginController class, define the
login()
method and insert the following code. It handles the server-side validation, redirects to admin dashboard if the logged in user is admin.
Incorporate the following code in app/Http/Controllers/Auth/LoginController.php file
<?phpnamespace 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
{
/*
|--------------------------------------------------------------------------
| 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 = RouteServiceProvider::HOME; /**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
} public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required'
]); $credentials = $request->only('email', 'password'); if(! auth()->attempt($credentials)){
return redirect()->route('login')
->with('error','Email-Address And Password Are Wrong.');
} if (auth()->user()->is_admin == 1) {
return redirect()->route('admin.home');
} return redirect()->route('home');
}
}
9-) Create Dummy Data using Seeder
So create a userseeder using the following command:
php artisan make:seeder UsersSeeder
Now, open the database/seeds/UsersSeeder.php file and insert the following data.
<?phpnamespace Database\Seeders;use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use App\Models\User;class UsersSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$usersData = [
[
'name' =>'Admin',
'email' =>'admin@example.com',
'is_admin' => 1,
'password' => Hash::make('12345678')
],
[
'name' => 'User',
'email' => 'user@example.com',
'is_admin' => 0,
'password' => Hash::make('12345678')
],
]; foreach ($usersData as $key => $val) {
User::create($val);
}
}
}
10-) Run Laravel Multi Auth App & Test
Evoke the laravel multi auth application with the given below command.
php artisan serve
Open the following URL on your browser on: http://127.0.0.1:8000/login
Admin Dashboard:
Use the below credentials for admin dashboard:
Email: admin@example.com
Password: 12345678
Here this view you will see after login using admin role
User Dashboard:
Use the below credentials for admin dashboard:
Email: user@example.com
Password: 12345678
Here this view you will see after login using normal user login
I hope you liked laravel multi auth tutorial step by step. So, don’t forget to share it with others, have a good day.