Laravel 10 Multi Authentication with Guards - WebJourney
In this modern age websites don’t have an option for multi-authentication. Now a days, most of the websites including e-commerce, real estate, educational institutions, hospitals, restaurants must have multi type users for maintaining their business growth and customer satisfaction. Today we will learn how to implement multi auth for a website. We will create two types of user like admin and normal user with the help of laravel 10 and guards.
What is multi authentication in laravel ?
If a application have more than one type of login register system (admin login, user login, editor login, accountant login etc) that is call multi authentication.
Why multiple authentication is need for a application?
Why we implement multi auth system in an application let’s understand this by an example. Suppose you have an ecommerce web application and it has two part , one is admin panel and other is user panel. In admin panel admins can manages all products and customer orders. On the other hand in user panel a user can manage only those data which is related to him i.e his order, profile info, review, comments etc. That’s why we need multi authentication.
What are Guards in laravel?
In laravel guards are the way how users are authenticated for each request. By default laravel provides few guards for authentication, which are located at config/auth. php file.
Following steps are required for multi authentication
1. Install laravel 10 app.
2. Create Database and connect with .env
3. Create model and migration as well as Controller
4. Create Middleware
5. Frontend scaffolding
6. Create required routes
7. Create and Modify required files
8. Test App
Step 1. Install laravel 10 app
Install laravel 10 app using composer
composer create-project laravel/laravel multi-authentication
Step 2. Create Database and connect with .env
Create a database multi_authentication and put database info in .env file
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=multi_authentication
DB_USERNAME=root
DB_PASSWORD=
Step 3. Create model and migration as well as Controller
Create model and migration files using the bellow artisan command. This will create a model Admin.php and a migration file 2023_02_24_065449 _create_admins_table.php
Php artisan make:model Admin -m
-m argument will create the migration file.
Now we have to modify migration file
2023_02_24_065449_ create_admins_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('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('admins');
}
};
Now run the migrate command to create admins table into our multi_authentication database.
php artisan migrate
Once the migrate successfully done we will run another command to create a controller.
Run the following artisan command for make a controller
php artisan make:controller AdminController
Step 4. Create Middleware
Middleware is the connector between a response and a request. Laravel middleware also verify the user of an application wheather he is authenticated or not. If the user is authenticated , it redirects to the homepage otherwise it redirect to the login page.
Let's now create a AdminMiddleware. To create that we have to execute the following artisan command. Created middleware can be seen at app/Http/Middleware directory.
php artisan make:middleware AdminMiddleware
After successfull execution of the above command we need to register the middleware into Kernel.php inside protected $middlewareAliases = [ ]; array.
app\Http\Kernel.php
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Now we need to do some changes in AdminMiddleware.php like bellow.
AdminMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if(!Auth::guard('admin')->check()){
return redirect('admin/login');
}
return $next($request);
}
}
Step 5. Frontend scaffolding
Laravel provided bootstrap scaffolding located in the laravel/ui
Composer package, which may be installed using Composer. Now we have to install laravel/ui package using the following command.
composer require laravel/ui
Once the laravel/ui
package has been installed, you may install the frontend scaffolding using the ui
Artisan command.
Run the bellow command to generate login / register scaffolding.
php artisan ui bootstrap --auth
Now Install npm dependencies by the bellow command.
npm install
Also Read: Laravel 9 form validation with custom message and display errors
Also Read: Laravel 9 ajax form validation and display error messages
Step 6. Create requird routes
Now we will create all the necessary routes and make some changes in web.php
resources/web.php
<?php
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('login-form',[AdminController::class,'login_form'])->name('login.form');
Route::post('login-functionality',[AdminController::class,'login_functionality'])->name('login.functionality');
Route::group(['middleware'=>'admin'],function(){
Route::get('logout',[AdminController::class,'logout'])->name('logout');
Route::get('dashboard',[AdminController::class,'dashboard'])->name('dashboard');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Step 7. Create and Modify required files
Update auth.php
We will update auth.php file located at config\auth.php to set guards for admin to assign session in driver and admins in provider.
We will also set providers for admins to assign eloquent in driver and Admin class in model.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
]
],
Update AdminController.php
Now we will write code for admin login with validation, logout inside AdminController.ph
App\Http\Controllers\ AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class AdminController extends Controller
{
//todo: admin login form
public function login_form()
{
return view('admin.login-form');
}
//todo: admin login functionality
public function login_functionality(Request $request){
$request->validate([
'email'=>'required',
'password'=>'required',
]);
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->route('dashboard');
}else{
Session::flash('error-message','Invalid Email or Password');
return back();
}
}
public function dashboard()
{
return view('admin.dashboard');
}
//todo: admin logout functionality
public function logout(){
Auth::guard('admin')->logout();
return redirect()->route('login.form');
}
}
Update Admin model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use HasFactory;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
}
Create login-form.blade.php
Now we need to create two blade file, One is admin login form and other one is admin dashboard where admin will logout after successfully logout.
We will also display laravel validation error message and a flash message above the login form if the login email or password is not match with the admin email or password stored into the database.
resources/views/admin/ login-form.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 10 multi authentication by WebJourney</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h2 class="py-5">Admin Login Form</h2>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if(Session::has('error-message'))
<p class="alert alert-info">{{ Session::get('error-message') }}</p>
@endif
<form action="{{ route('login.functionality') }}" method="post">
@csrf
<div class="mb-3">
<label class="form-label">Email address</label>
<input type="email" class="form-control" name="email" placeholder="Enter Email">
</div>
<div class="mb-3">
<label class="form-label">Email address</label>
<input type="password" class="form-control" name="password" placeholder="Enter Password">
</div>
<input type="submit" class="btn btn-primary" value="Admin Login">
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
resources/views/admin/dashboard.blade.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 10 multi authentication by WebJourney</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h2 class="py-5">Admin Dashboard</h2>
<h4 class="py-2">Welcome !!</h4>
<a href="{{ route('logout') }}" class="btn btn-danger">Logout</a>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
Create a Admin
Now we will insert an admin data into the database for checking admin login and logout functionality. To do that we need to modify DatabaseSeeder.php like bellow.
database/seeders/DatabaseSeeder.php
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
// \App\Models\User::factory(10)->create();
// \App\Models\User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
\App\Models\Admin::create([
'name' => 'Web Journey',
'email' => 'webjourney@gmail.com',
'username' => 'webjourney',
'password' => Hash::make('12345678'),
]);
}
}
Run the following command to insert the admin.
php artisan db:seed
Step 8. Test App
Now we will test authentication for both admin and normal user. Run the following two command in two different terminal.
npm run dev
After run this command you will see in your terminal like bellow
npm run dev compile the JavaScript and CSS files written for laravel application.
Also execute the following one.
php artisan serve
Now you will see in terminal like bellow.
Copy and paste the url http://127.0.0.1:8000 and hit enter
Now hit the url for admin login http://127.0.0.1:8000/login-form
Hope this will help you a lot. Thanks
If you like what you are reading, please think about buying us a coffee as a token of appreciation.
We appreciate your support and are committed to providing you useful and informative content.
We are thankful for your ongoing support
You May Read Bellow Articles:
Laravel 9 live search data in a table using ajax.
How to send SMS in laravel 9 using Twilio SMS API-Webjourney
Laravel 9 pdf invoice generate and download with barryvdh dompdf
How to create multi language website by laravel 9