In this blog post, we learn How to Make Multi Auth in Laravel 6.2. we are creating two tables one for the user and another for admin.
In this blog post, we learn how to make multi auth in Laravel 6. In this tutorial we create a new auth with a new table for Admin. admin has its own auth, login page totally separate from users.
Step: 1 Create a new Laravel 6 Application in your system.
laravel new authapp
using this command you can create a new Laravel application.
Step: 2 Create default, Auth, In Laravel Application,
we need to use default auth of Laravel for the user and then create a new auth for Admin. first create default auth using this command. In Laravel 6 have a new command to make auth Laravel 6.*, Auth
composer require laravel/ui --dev
php artisan ui vue --auth
After creating this auth we need to migrate everything. use can migrate using this simple command.
php artisan migrate
But Before Migrate you must be connected with your database.
Step: 3 Create a new Model for Admin.
php artisan make:model Models/Admin -m
After creating a model for admin you should add this following code in Admin Model.
Admin.php
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'firstname', 'midname', 'lastname', 'email', 'address', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
and add some columns in the admin migration table like name password and other details.
Migrate admin table
php artisan migrate
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('midname');
$table->string('lastname');
$table->string('email')->unique();
$table->string('address')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
Step: 4 Add custom guard in the config file
Now we need to add some custom guards and providers for admins.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
Step: 5 Create A view to Admin Login.
Create a simple login page for admin in the auth folder.
auth / admin_login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=UTF-8>
<meta name=viewport content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin=anonymous>
<title>Admin</title>
</head>
<body>
<div >
<div >
<div ></div>
<div >
<div >
<div >
<form id="sign_in_adm" method="POST" action="{{ route('admin.login.submit') }}">
{{ csrf_field() }}
<h1>Admin Login</h1>
<div >
<input type=email name=email placeholder="Email Address" value="{{ old('email') }}" required autofocus>
</div>
@if ($errors->has('email'))
<span ><strong>{{ $errors->first('email') }}</strong></span>
@endif
<br>
<div >
<input type=password name=password placeholder="Password" required>
</div>
<br>
<div >
<button type=submit >SIGN IN</button>
</div>
</form>
</div>
</div>
</div>
<div ></div>
</div>
</div>
</body>
</html>
Create an admin dashboard page. admin.blade.php in view Folder. after login admin redirect on this page.
admin.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=UTF-8>
<meta name=viewport content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin=anonymous>
<title>Admin Dashboard</title>
</head>
<body>
<div >
<div >
<div ></div>
<div >
<div >
<div >
<h1>Welcome To Admin Dashboard</h1>
</div>
</div>
<a href="/admin/logout">Logout</a>
</div>
<div ></div>
</div>
</div>
</body>
</html>
Step: 6 Create a new controller for handle admin Dashboard
Now we need to create a new controller to admin where we add some code to handle admin login. you can create a controller using this command.
php artisan make:controller Auth/AdminController
After create controller add the flowing code in AdminController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* show dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin');
}
}
Step: 7 Create Admin controller for admin Login
php artisan make:controller Auth/AdminLoginController
Auth\AdminLogincontroller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Route;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin', ['except' => ['logout']]);
}
public function showLoginForm()
{
return view('auth.admin_login');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('admin.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout()
{
Auth::guard('admin')->logout();
return redirect('/admin');
}
}
Step: 7 Create some routes for admin.
Now we will set our routes; routes/web.php
Route::prefix('admin')->group(function() {
Route::get('/login','Auth\[email protected]')->name('admin.login');
Route::post('/login', 'Auth\[email protected]')->name('admin.login.submit');
Route::get('logout/', 'Auth\[email protected]')->name('admin.logout');
Route::get('/', 'Auth\AdminCon[email protected]')->name('admin.dashboard');
}) ;
After that, we need to add some code for handle admin login when an admin wants to log in or back to the admin login page after admin logout.
Add flowing function in app/Exceptions/Handler.php
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Arr;
class Handler extends ExceptionHandler
{
protected $dontReport = [
];
public function report(Exception $exception)
{
parent::report($exception);
}
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = Arr::get($exception->guards(), 0);
switch ($guard) {
case 'admin':
$login='admin.login';
break;
default:
$login='login';
break;
}
return redirect()->guest(route($login));
}
}
And now we need to tell Laravel If the admin or user login is successful, redirect to the right dashboard of the specific guard.
This is done in the RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
// if (Auth::guard($guard)->check()) {
// return redirect(RouteServiceProvider::HOME);
// }
// return $next($request);
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
default:
if (Auth::guard($guard)->check()) {
return redirect('/');
}
break;
}
return $next($request);
}
}
Ok, here all is done now you can log in as admin and user with different auth. To log in with Admin use flowing link
Now we complete tutorial on How to Make Multi Auth in Laravel 6 different tables for admin auth. if you have any issue regarding these tutorials feel free to ask in the comment box,
Thanks…

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.