How To Make Multi Auth In Laravel 7

How To Make Multi Auth In Laravel 7 in this blog, post we create another auth for admin in laravel 7.

We know laravel give us a default auth for users but in some cases we need another auth for admin. we see need a secure login auth for admin.

So first here I am using a fresh laravel application so first, install a laravel application create user auth.

Step: 1 Create a New Laravel 7 Application

create a new Laravel 7 Application using this command.

laravel new multiauth

After successfully create a project run some command to generate default auth.

composer require laravel/ui --dev

and

php artisan ui bootstrap --auth

after that run this following command

npm install && npm run dev 

Ok, We completed user auth but we need to create another auth for admin to multi auth.

Step: 2 Now Create a modal for admin

we are a new modal and table for admin using this command

php artisan make:model Models/Admin -m

Add some code in admin modal

Models / 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 = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
   }

admin some code for admin table columns

<?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('name');
            $table->string('email')->unique();
           	$table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('admins');
    }
}

Connect the Laravel application with Your database and run this command to migrate the user table.

php artisan migrate

Now we need to modify auth.php. 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\User::class,
        ],
        
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
        
    ],

Step: 3 Create Admin Login Page and Admin Dashboard Page

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>

admin.bladephp  create admin dashboard page when admin redirect after login

<!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: 4 Create two new Controller for admin to the hander admin dashboard and admin login page

Run this command to create an AdminController in the auth folder.

php artisan make:controller Auth/AdminController

Add some code in AdminController.php

<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
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');
    }
}

Run this command for create an admin login Controller.

php artisan make:controller Auth/AdminLoginController

AdminLoginController.php

<?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])) {
        // 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: 5 Create some routes for admin.

add some route for handle admin.

Route::prefix('admin')->group(function() {
    Route::get('/login','Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
    Route::get('logout/', 'Auth\AdminLoginController@logout')->name('admin.logout');
    Route::get('/', 'Auth\AdminController@index')->name('admin.dashboard');
   }) ;

Step: 6 Handle admin redirection after login

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));
    }
}

After that, we need to change auth redirection when admin login it should be redirected on right place such as admin dashboard. update the following code in redirect if authenticated.php

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 we completed tutorials on How To Make Multi Auth In Laravel 7. run your application using this flowing command.

php artisan serve

and visit this URL to login admin login page. //localhost:8000/admin 

Thanks