
Laravel 8 Multi Auth System Different login for user and admin
How to create a multi-user auth system in Laravel 8. Different login for user and admin configuration Larave8. Let,s Start composer create-project –prefer-dist laravel/laravel UserRegistrationSystem cd /UserRegistrationSystem create .env file in …
How to create a multi-user auth system in Laravel 8. Different login for user and admin configuration Larave8.
Let,s Start
- composer create-project –prefer-dist laravel/laravel UserRegistrationSystem
- cd /UserRegistrationSystem
- create .env file in a root directory
UserRegistrationSystem~/touch .env
DB_DATABASE=your databse name
DB_USERNAME=Your database username
DB_PASSWORD=Your database password
composer require laravel/breeze
php artisan breeze:install
npm install
npm run dev
php artisan migrate
php artisan serve
Now you can see in the right side top bar login and register link appear

Create model as named Admin and migrate table using below command
php artisan make:model Admin -m
- Go to the migrations folder and open the newly created 2021_10_07_154242_create_admins_table
- Paste the below code
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
Go to the Model folder and open the newly created Admin model and paste the below code
<?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 string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Now Set Route for Admin, go to the routes folder and open web.php file, and paste the below code
Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function(){
Route::namespace('Auth')->group(function(){
//login route
});
});
Go to the providers folder and open RouteServiceProvider.php uncomment the line
// protected $namespace = 'App\\Http\\Controllers';
protected $namespace = 'App\\Http\\Controllers';
- Create a Admin/Auth folder under the controller folder
- Under the Admin/Auth folder create a file named AuthenticatedSessionController.php and paste the below code
<?php
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('admin.auth.login');
}
/**
* Handle an incoming authentication request.
*
* @param \App\Http\Requests\Auth\LoginRequest $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::ADMIN_HOME);
}
/**
* Destroy an authenticated session.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
Go to the providers folder and open the file RouteServiceProvider.php and paste the below code
public const ADMIN_HOME = '/admin/dashboard';
- Now create a folder Admin/Auth under the resources/views folder
- Create a file named login.blade.php under the Admin/Auth folder and paste the below code
<x-guest-layout>
<x-auth-card>
<x-slot name="logo">
<a href="/">
<x-application-logo class="w-20 h-20 fill-current text-gray-500" />
</a>
Admin Login Page
</x-slot>
<!-- Session Status -->
<x-auth-session-status class="mb-4" :status="session('status')" />
<!-- Validation Errors -->
<x-auth-validation-errors class="mb-4" :errors="$errors" />
<form method="POST" action="{{ route('login') }}">
@csrf
<!-- Email Address -->
<div>
<x-label for="email" :value="__('Email')" />
<x-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
</div>
<!-- Password -->
<div class="mt-4">
<x-label for="password" :value="__('Password')" />
<x-input id="password" class="block mt-1 w-full"
type="password"
name="password"
required autocomplete="current-password" />
</div>
<!-- Remember Me -->
<div class="block mt-4">
<label for="remember_me" class="inline-flex items-center">
<input id="remember_me" type="checkbox" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" name="remember">
<span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
</label>
</div>
<div class="flex items-center justify-end mt-4">
@if (Route::has('password.request'))
<a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
{{ __('Forgot your password?') }}
</a>
@endif
<x-button class="ml-3">
{{ __('Log in') }}
</x-button>
</div>
</form>
</x-auth-card>
</x-guest-layout>
Go to the web.php file add route
Route::get('login','AuthenticatedSessionController@create')->name('login');
- Create an Admin Login link
- open welcome.blade.php file and paste <a href=”{{ route(‘admin.login’) }}”> Admin Login
Now create a post for admin login
Route::post('login','AuthenticatedSessionController@store')->name('adminlogin');
Now go to the admin/auth/login.blade.php file and change the form action
<form method="POST" action="{{ route('admin.adminlogin') }}">
Create seed for admin using below command( we can manually import admin data but there will be password issue because we are inserted password has format).
php artisan make:seed AdminSeeder
- Now you can see AdminSeeder.php file under the database→seeders→AdminSeeder.php
- Paste the below code
AdminSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Admin;
class AdminSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
$admin =[
'name'=>'Admin',
'email'=>'admin@gmail.com',
'password'=> bcrypt('password')
];
Admin::create($admin);
}
}
Now we have seed the data into the database using below command
php artisan db:seed
Database seeding completed successfully.
we have to call DatabaseSeeder. Go to the DatabaseSeeder.php file and add the below code
public function run()
{
// \App\Models\User::factory(10)->create();
$this->call(AdminSeeder::class);
}
php artisan migrate:fresh --seed
- Now create a guard for admin
- Http→Model→Admin.php
below the use HasApiTokens, HasFactory, Notifiable;
protected $guard= 'admin';
Now go to the config folder and define the newly created Admin gurd on auth.php file.
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
Then go-to the Http→Middleware→RedirectIfAuthenticated.php and replace the below code
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
if(Auth::guard($guard)->check()){
if($guard == 'admin'){
return redirect(RouteServiceProvider::ADMIN_HOME);
}
}
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
- Next, go to the Http→controllers→Admin→Auth→AuthenticatedSessionController.php
- under the store function chek data is coming or not
dd($request->all());
Login with /login/admin
You can see successfully data has returned
- Now go to the again AuthenticatedSessionController.php and change LoginRequest to AdminLoginRequest
- Next, go to the Requests→Auth and create a new file AdminLoginRequest.php. paste the below code
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class AdminLoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::guard('admin')->attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*
* @return string
*/
public function throttleKey()
{
return Str::lower($this->input('email')).'|'.$this->ip();
}
}
Create a dashboard for admin
- resources→views→admin- create a file name dashboard.blade.php
- Now create a route for the admin dashboard under web.php file
Route::get('dashboard','HomeController@index')->name('dashboard');
- Now create a HomeController under Admin folder using below command
php artisan make:controller Admin/HomeController
For windows, user command will
php artisan make:controller Admin\HomeController
And Linux User command will
php artisan make:controller Admin/HomeController
HomeController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class HomeController extends Controller
{
//
public function index()
{
return view('admin.dashboard');
}
}
Now you can see the error of Navigation
- Now we will solve the error
- simply compy the user layout folder and past it to admin folder
- Next, go to the app/View/Components folder and create AdminLayout and paste the below code
AdminLayout.php
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class AdminLayout extends Component
{
/**
* Get the view / contents that represents the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('admin.layouts.app');
}
}
resources→views→admin→layouts→app.blade.php
@include('admin.layouts.navigation')
Note: Under the Admin -layouts folder open navigation.blade.php file and replace all dashboard to admin.dashboard and change {{ Auth::user()->name }} to {{ Auth::guard(‘admin’)->user()->email }}
And most important things to do
Open admin→dashboard.blade.php change <x-app-layout> to<x-admin-layout>
Now you can see I logged in as an admin but when I typed but still access the admin login page, So it should not access the page, now we will solve the issue.
- Open the welcome.blade.php file and add the below code
<div class="flex justify-center pt-8 sm:justify-start sm:pt-0">
@auth('admin')
<a href="{{ route('admin.dashboard') }}"> Admin dashboard
@else
<a href="{{ route('admin.login') }}"> Admin Login
@endauth
</div>
- Now configure logout button for admin
- Go to the resources→views→admin→layouts→navigation.blade.php and replace with {{ route(‘logout’) }} to {{ route(‘admin.logout’) }}
- Now we have to create logout route for admin
- Go to the web.php file add the route below
Route::post('logout','Auth\AuthenticatedSessionController@destroy')->name('logout');
- Now go to the Http→Controllers→Admin→Auth→AuthenticatedSessionController.php and replace with Auth::guard(‘web’)->logout(); to Auth::guard(‘admin’)->logout(); because we need to logout for admin guard.
Now you can see I have logged in as an admin but still access the admin login page. So, it should not access if already logged in, So, for this solution, we create middleware and set configuration
php artisan make:middleware AdminMiddleware
Now got to the middleware folder and open AdminMiddleware.php file and paste below code
AdminMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Auth;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if(!Auth::guard('admin')->check()){
return redirect()->route('admin.lgin');
}
return $next($request);
}
}
Next, go to the web.php file and create a middleware group, and put the protected Url in a middleware group
Route::middleware('admin')->group(function(){
Route::get('dashboard','HomeController@index')->name('dashboard');
});
Now you can see the error Target class admin does not exist. because we have to register the path of admin middleware with kerlnel.php file
- Now register middleware with kernel.php file
- Go to the app→Http→ kernel.php file and paste the below code on protected $routeMiddleware
'admin'=> \App\Http\Middleware\AdminMiddleware::class;
Now you can see we can’t access the dashboard if I am not logged in but still we have another problem that is we can access the login page as I have already logged in. it should not access if I have already logged in. So we need to add middleware where login route running
middleware('guest:admin')
previous
Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function(){
Route::namespace('Auth')->group(function(){
//login route
Route::get('login','AuthenticatedSessionController@create')->name('login');
Route::post('login','AuthenticatedSessionController@store')->name('adminlogin');
});
After
Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function(){
Route::namespace('Auth')->middleware('guest:admin')->group(function(){
//login route
Route::get('login','AuthenticatedSessionController@create')->name('login');
Route::post('login','AuthenticatedSessionController@store')->name('adminlogin');
});
Thanks for reading…