How to Make Multi Auth in Laravel 6

  • Brijpal Sharma

    October 13th, 2019 , Posted On:- Web Development

    php laravel 6


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/Admins -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.

<?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.

<form id="sign_in_adm" method="POST" action="{{ route('admin.login.submit') }}">
   {{ csrf_field() }}
   <div class="input-group">
      <span class="input-group-addon"> <i class="zmdi zmdi-account"></i> </span>
      <div class="form-line">
         <input type="email" class="form-control" name="email" placeholder="Email Address" value="{{ old('email') }}" required autofocus>
      </div>
      @if ($errors->has('email'))
      <span class="text-danger"><strong>{{ $errors->first('email') }}</strong></span>
      @endif
   </div>
   <div class="input-group">
      <span class="input-group-addon"> <i class="zmdi zmdi-lock"></i> </span>
      <div class="form-line">
         <input type="password" class="form-control" name="password" placeholder="Password" required>
      </div>
   </div>
   <div>
      <div class="">
         <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }} id="rememberme" class="filled-in chk-col-pink">
         <label for="rememberme">Remember Me</label>
      </div>
      <div class="text-center">
         <button type="submit" class="btn btn-raised waves-effect g-bg-cyan">SIGN IN</button>
      </div>
   </div>
</form>

 

Step: 6 Create a new controller for handle admin login

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 some routes for admin.

Now we will set our routes; routes/web.php

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('/', 'AdminController@index')->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

public function handle($request, Closure $next, $guard = null)
    {
      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

http://localhost:8000/admin

Now we complete tutorial on How to Make Multi Auth in Laravel 6 different tables for admin auth. if you have any issue redarding these tutorials feel free to ask in the comment box,

Thanks...


About Author
  • user profile
    Brijpal Sharma

    brijpalsharma99@gmail.com, January 29th, 2018

    Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

1 Comment

user profile image
November 13th, 2019 - 5:05AM

I would like to know where I can find AdminLoginController.


You must be logged in to post a comment.