Multi auth is the first step to create any project. You must need to know how to separate and secure authentication for both user and admin. In laravel, we can do it various way. Today we use laravel breeze authentication system for creating separate user and admin login system where user also can register but admin not. You created separate guard, model, controller, db table everything for both admin and user. So it is fully secure. Follow the steps mentioned below, so you will able to do it too. This is the easiest step by step tutorial for you to create multi authentication system using laravel 10.
Step One – Create a Fresh Laravel Project
To do so, simply run the follow command
composer create-project laravel/laravel authapp
Step Two – Install Breeze Authentication System
Run the following command one by one
composer require laravel/breeze --dev
php artisan breeze:install blade
Before running the php artisan migrate, go to your project folder and find .env file, there provide your database information. To create a fresh new database, use phpmyadmin dashboard/panel.
Now run these command
php artisan migrate
npm install
npm run dev
Step Three – Create model and migration for admin
php artisan make:model Admin -m
Step Four – Go to admin migration file and add this column to your table
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
Step Five – Go to Admin model file and replace the code with it
<?php
namespace 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;
class Admin extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
Step Six – Also add this protected guard name to Admin model
protected $guard = 'admin';
Next, we have to create this guard. To do so, go to config folder and inside that, you will find auth.php, go to that file and find out guards. There you will see, one guard already available which is web, now copy the web guard code and paste just below. Next change the name from web to admin and provider value to admins which is users in web guard. Lastly go below of that file code, you will find there providers. Already there users provider available. Copy the code and paste just below of users provider and change the name from users to admin and also change the model path to Admin model path.
'model' => App\Models\Admin::class,
Step Seven – Now run the migration for adding admin table to our database
Step Eight – Go to inside http folder, then controller folder. Copy the Auth folder all file from there. Next inside controller, create another folder called AdminAuth and paste all the copied files to it. Lastly change all the AdminAuth files namespace because it is different now as we copy paste them to a new folder.
Step Nine – Now open the file AuthenticatedSessionController which is inside our AdminAuth folder, this file is responsible for login user. In this file, you will get the code of, when we access the login route, what view to display, functions that responsible for login and logout.
Now change the return view in create funtion to admin.auth.login, also change the RouteServiceProvider to ADMIN_DASHBOARD which is now HOME. As this ADMIN_DASHBOARD is not exists yet so it will give error. To solve that, go to your RouteServiceProvider file inside provider folder, and copy public const HOME = ‘/dashboard’; and paste once, change the HOME to ADMIN_DASHBOARD and route to /admin/dashboard. This is the url in which admin will be redirect after successful login.
Next we have to create this view. To do so, go to your view folder, create one admin folder there, copy your previous auth folder and paste it to the admin folder you just created.
Lastly here in AuthenticatedSessionController, in destroy method, change auth guard to admin which is web now, so when logged out, it logout the admin.
Step Ten – Now go to Request Folder, copy and paste the full Auth folder, change the name to AdminAuth. Then open the inside file name LoginRequest and change the namespace accordingly. Next in the authenticate function at same file, add guard admin ~
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::guard('admin')->attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
Now go to your AutheticatedSessionController file again, change the use App\Http\Requests\Auth\LoginRequest; to
use App\Http\Requests\AdminAuth\LoginRequest;
I don’t allow admin registration. For that reason, i can delete RegisteredUserController from my AdminAuth controller folder. If you want to keep, the changes we made in AuthenticatedSessionController file, almost same changes you need to do in all the files. For me, only admin login is enough.
Step Eleven – Go to web.php in route folder, create the admin dashboard route mentioned below ~
Route::get('/admin/dashboard', function () {
return view('admin.dashboard');
})->middleware(['auth:admin', 'verified'])->name('admin.dashboard');
also require DIR.’/adminauth.php’;
to create adminauth.php, copy the auth.php from routes folder and paste to routes folder and change the name of it. This file will be responsible for all the authentication related routes. Change the all use file path from Auth folder to AdminAuth folder after controller. Also change the middleware group to middleware(‘guest:admin’). Change all the route and there name as well. Like login to admin/login and name from login to admin.login. Do the same thing for below auth route group. First change the middleware to auth:admin then all other changes like before. You can just copy paste my full code of adminauth.php if you find it hard.
<?php
use App\Http\Controllers\AdminAuth\AuthenticatedSessionController;
use App\Http\Controllers\AdminAuth\ConfirmablePasswordController;
use App\Http\Controllers\AdminAuth\EmailVerificationNotificationController;
use App\Http\Controllers\AdminAuth\EmailVerificationPromptController;
use App\Http\Controllers\AdminAuth\NewPasswordController;
use App\Http\Controllers\AdminAuth\PasswordController;
use App\Http\Controllers\AdminAuth\PasswordResetLinkController;
use App\Http\Controllers\AdminAuth\VerifyEmailController;
use Illuminate\Support\Facades\Route;
Route::middleware('guest:admin')->group(function () {
Route::get('admin/login', [AuthenticatedSessionController::class, 'create'])
->name('admin.login');
Route::post('admin/login', [AuthenticatedSessionController::class, 'store']);
Route::get('admin/forgot-password', [PasswordResetLinkController::class, 'create'])
->name('admin.password.request');
Route::post('admin/forgot-password', [PasswordResetLinkController::class, 'store'])
->name('admin.password.email');
Route::get('admin/reset-password/{token}', [NewPasswordController::class, 'create'])
->name('admin.password.reset');
Route::post('admin/reset-password', [NewPasswordController::class, 'store'])
->name('admin.password.store');
});
Route::middleware('auth:admin')->group(function () {
Route::get('admin/verify-email', EmailVerificationPromptController::class)
->name('admin.verification.notice');
Route::get('admin/verify-email/{id}/{hash}', VerifyEmailController::class)
->middleware(['signed', 'throttle:6,1'])
->name('admin.verification.verify');
Route::post('admin/email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware('throttle:6,1')
->name('admin.verification.send');
Route::get('admin/confirm-password', [ConfirmablePasswordController::class, 'show'])
->name('admin.password.confirm');
Route::post('admin/confirm-password', [ConfirmablePasswordController::class, 'store']);
Route::put('admin/password', [PasswordController::class, 'update'])->name('admin.password.update');
Route::post('admin/logout', [AuthenticatedSessionController::class, 'destroy'])
->name('admin.logout');
});
Step Twelve – Now go to your view folder, inside that admin folder then auth folder. Open login view and inside action route change it with correct one like this ~ action=”{{ route(‘admin.login’) }}”, now change all other view file action route same way which inside admin/auth folder. If you have any other routes in these files, change them also with correct one.
Step Thirteen – We dont have the admin.dashboard view, let’s just create it now. I just created a dashboard.blade.php inside admin folder and add one h2 tag there with a text of Admin Dashboard. That’s all i need for now. Later you can add any template.
Step Fourteen – Now go to your http folder then go inside middleware folder. open RedirectIfAuthenticated file and inside handle function you will see a foreach loop. Inside the loop, before the if condition paste this if block
if ($guard=="admin" && Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::ADMIN_DASHBOARD);
}
So it will redirect us perfectly after successful login, logout.
Final Step – Everything done. Now go to your phpmyadmin dashboard. Open your database, find the admins table. Insert one record and come back to your project, test it.
If you find this written post hard to follow, you can also watch this video to understand more easily.
Without using any multiauth package, it’s a long process to build multiauth in Laravel. Although it’s not hard at all. Once you done, it will give you all the satisfaction you need. That’s it for today. Bookmark me to get new post more often. Thank you.
Laravel Admin & User Login ~ Multi Auth in Laravel 10