Laravel provides default authentication with login register password reset etc and with fortify, they provide two factor authentication also. But there are no multiple authentications in laravel by default. So if you need multi authentication in you laravel application, then you have to implement it from scratch. 

In this laravel 9 multi auth tutorial, I will show you from scratch laravel 9 multi auth create multiple authentication in laravel application. So if you need multi auth, you have no worries. Just follow the steps I have implemented here. 

Though using guard, we can create multiple authentication in laravel with a different table. But, in this tutorial, I am not gonna use a guard. I will use middleware to handle the same table multi auth in laravel 9 with different roles. See the preview of laravel multi auth tutorial:

Login as an admin

laravel-multi-authentication-example

Login as a normal user

laravel-9-multi-auth-example

Step 1: Install Laravel

First of all, we need to get a fresh Laravel 9 version application using the bellow command, So open your terminal OR command prompt and run the bellow command to start laravel 9 multi auth create multiple authentication in laravel:

composer create-project laravel/laravel example-app

 

Step 2: Connect Database

After successfully installing the laravel app and then configuring the database setup. We will open the ".env" file and change the database name, username and password in the env file.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

 

Read also: Laravel 9 Email Based Two Factor (2FA) Authentication

 

Step 3: Create Migration and Model

In this step, we need to add a new row "is_admin" in users table and model. then we need to run a migration. so let's change that on both files.

database/migrations/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');
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_admin')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

 

Now update the user model by replacing it with the below code:

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;
  
class User extends Authenticatable
{
    use HasFactory, Notifiable;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'is_admin'
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

 

Now you have to run this migration by following the command:

php artisan migrate

 

Read also: Laravel 9 Google Two Factor (2FA) Authentication Tutorial

 

Step 5: Create Auth Scaffold

Here, we will use laravel ui package and create auth scaffold with the bootstrap framework. let's follow bellow command:

composer require laravel/ui

 

Now create a simple bootstrap auth system:

php artisan ui bootstrap --auth

 

And run npm i and npm run dev to compile javascript assets.

 

Step 5: Create Middleware

In this step, we need to create admin middleware that will allow only admin access users to that routes. so let's create an admin user with the following steps.

php artisan make:middleware IsAdmin

 

Now update the middleware with the below code:

app/Http/middleware/IsAdmin.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
   
class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->is_admin == 1){
            return $next($request);
        }
   
        return redirect(‘home’)->with(‘error’,"You don't have admin access.");
    }
}

 

And now register the middleware by adding it to the Kernel.php file.

app/Http/Kernel.php

....
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::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 the admin user home page so let's add that route in the 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('admin/home', [HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');

 

Step 7: Create Controller

Here, we need to add the adminHome() method for the admin route in HomeController. so let's add like as below:

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('home');
    }
  
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function adminHome()
    {
        return view('adminHome');
    }
    
}

 

Step 8: Create Blade file

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

resources/views/home.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">Dashboard</div>
                <div class="card-body">
                    You are normal user.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Now create an admin home blade file and update it like this: 

resources/views/adminHome.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">Dashboard</div>
                <div class="card-body">
                    You are Admin.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Step 9: Create LoginController

In this step, we will change on LoginController, when the user will login then we redirect according to user access. if a normal user then we will redirect to the home route and if admin user then we redirect to the admin route. so let's change.

app/Http/Controllers/Auth/LoginController.php

<?php
  
namespace App\Http\Controllers\Auth;
   
use App\Http\Controllers\Controller;
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','Email-Address And Password Are Wrong.');
        }
          
    }
}

 

Step 10: Create Seeder

We will create a seeder for creating new admin and normal users. so let's create a seeder using the following command:

php artisan make:seeder CreateUsersSeeder

 

Now update the newly created seeder file:

database/seeds/CreateUsersSeeder.php

<?php
  
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@laravelia.com',
                'is_admin'=>'1',
               'password'=> bcrypt('secret'),
            ],
            [
               'name'=>'User',
               'email'=>'user@laravelia.com',
                'is_admin'=>'0',
               'password'=> bcrypt('secret'),
            ],
        ];
  
        foreach ($user as $key => $value) {
            User::create($value);
        }
    }
}

 

Now time to run the seeder. So run by the below command:

php artisan db:seed --class=CreateUsersSeeder

 

Read also: How To Implement Remember Me With Expiration Time In Laravel?

 

Ok, now we are ready to go and test laravel 9 multi auth tutorial. So let's run the project using this command:

php artisan serve

 

Now you can test our application by visiting the below URL:

URL
http://127.0.0.1:8000/

 

Conclusion

Now we know laravel multi authentication system implementation. Hope this laravel 9 multi auth create multiple authentication in laravel tutorial will help you to create multi authentication system in laravel.

Category : #laravel

Tags : #laravel , #laravel auth