In this article, we will learn about how to implement multiple authentications in Laravel 9 application.

Steps for implementing multiple authentications

Step 1: Install Laravel Application

Step 2: Database Configuration

Step 3: Update Migration and Model

Step 4: Create Auth by Laravel UI Package

Step 5. Create Middleware

Step 6: Create Route

Step 7: Add Method on Controller

Step 8: Create Blade file

Step 9: Update on LoginController

Step 10: Create Seeder

Step 1: Install Laravel Application

First, open Terminal and run the following command to create a new Laravel application:

composer create-project --prefer-dist laravel/laravel multi-auth

Step 2: Database Configuration

In second step, we will make database configuration

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=multiauth
DB_USERNAME=root
DB_PASSWORD=

Step 3: Update Migration and Model

In this step, we need to add new column “is_admin” in users table and model. than we need to run migration.

database\migrations\2014_10_12_000000_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->boolean('is_admin')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

app/Models/User.php

<?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 User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'is_admin',
        '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',
    ];
}

Now we need to run migration.

php artisan migrate

Step 4: Create Auth by Laravel UI Package

Run following commands:

Laravel UI Package

composer require laravel/ui 

Generate auth

php artisan ui bootstrap --auth 
npm install
npm run dev

Step 5. Create Middleware

After that, we need to create admin middleware that will allows only admin access users to that routes. so let’s create admin user with following steps.

php artisan make:middleware IsAdmin

app/Http/middleware/IsAdmin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->is_admin == 1){
            return $next($request);
        }
   
        return redirect(‘home’)->with(‘error,"Sorry ,You are not eligible to access this action.");
    }
}

app/Http/Kernel.php

    ......
protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'is_admin' => \App\Http\Middleware\IsAdmin::class,
    ];
    ......

Step 6: Create Route

Here, we need to add one more route for admin user home page so let’s add that route in web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('admin/home', [HomeController::class, 'adminDashboard'])->name('admin.home')->middleware('is_admin');

Step 7: Add Method on Controller

Here, we need add adminDashboard() method for admin route in HomeController. so let’s add like as bellow:

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('user-dashboard');
    }

     /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function adminDashboard()
    {
        return view('admin-dashboard');
    }
}

Step 8: Create Blade file

In this step, we need to create new blade file for admin and update for user blade file. so let’s change it.

resources/views/admin-dashboard.blade.php

@extends('layouts.app')
   
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Admin Dashboard</div>
                <div class="card-body">
                    Welocome to admin dashboard.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

resources/views/user-dashboard.blade.php

@extends('layouts.app')
   
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">User Dashboard</div>
                <div class="card-body">
                    Welcome to user dashboard
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 9: Update on LoginController

Open the app/Http/Controllers/Auth/LoginController.php and add the logic.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function login(Request $request)
    {   
        $input = $request->all();
   
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
   
        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
        {
            if (auth()->user()->is_admin == 1) {
                return redirect()->route('admin.home');
            } else {
                return redirect()->route('home');
            }
        }else{
            return redirect()->route('login')->with('error','Sorry . Entered Email And Password is Wrong.');
        }
          
    }
}

Step 10: Create Seeder

We will create seeder for create new admin and user. so let’s create seeder using following command:

php artisan make:seeder CreateUsersSeeder

database/seeds/CreateUsersSeeder.php

<?php

namespace Database\Seeders;  

use Illuminate\Database\Seeder;
use App\Models\User;
   
class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user = [
            [
               'name'=>'Admin',
               'email'=>'admin@victorzilla.com',
               'is_admin'=>'1',
               'password'=> bcrypt('Test@1234'),
            ],
            [
               'name'=>'User',
               'email'=>'user@victorzilla.com',
               'is_admin'=>'0',
               'password'=> bcrypt('Test@1234'),
            ],
        ];
  
        foreach ($user as $key => $value) {
            User::create($value);
        }
    }
}

Update logic on DatabaseSeeder

database\seeders\DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();
        $this->call([CreateUsersSeeder::class]);
    }
}

Now , Run below command .

php artisan db:seed

Ok, now Run the application

php artisan serve

Output : Dashboard show after admin login

Output : Dashboard show after user login

Categorized in: