How To Create Multi Auth (Authentication) In Laravel 8


This time learn Laravel 8 multi authentication tutorial. You will learn how to create multi auth system in laravel using middleware.

Multiple auth system means multiple users can log in to one application according to roles and use multiple pages.

Multiple authentications are very important in the large application of laravel projects. Authentication is the process of recognizing user and admin credentials.

Create a middleware for checking the user’s role in multiple authentications. It is an admin or normal user. Then create middleware name is Admin and configuration in the kernal.php file and also in the route file.

How To Create Multi Auth (Authentication) In Laravel 8 Tutorial

Multiple Authentication in Laravel 8 (Admins + Users)

Step 1: Install Laravel 8 App

Open the terminal and execute the below command to download the laravel 8 fresh setup on your system:

composer create-project --prefer-dist laravel/laravel LaraMulti
Step 2: Connecting App To Database

After successfully download or install laravel Application, Go to your project .env file and set up database credential:

  DB_CONNECTION=mysql 
  DB_HOST=127.0.0.1 
  DB_PORT=3306 
  DB_DATABASE=here your database name here
  DB_USERNAME=here database username here
  DB_PASSWORD=here database password here
Step 3: Setting Up Migration And Model

Add the is_admin column in the user's table using the migration file. So, Open the creates_users_table.php migration file, which is placed on Database/migration, and update the following field for admin.

$table->boolean('is_admin')->nullable();


Next open app/User.php and update the below field name is_admin here:

<?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',
    ];
}

add is_admin filed after that will use the below command for creating this field into the database.

php artisan migrate

We create a built-in authentication system. Use the below command for creating the default auth system in laravel. And change laravel built-in auth system to multi auth system this tutorial.

This command will create a route, controllers, and views files for Laravel Login Authentication and registration. It means to provide a basic laravel login authentication and registration Complete system. Then open the command prompt and type the below command.

Then install laravel 8 UI in your project using the below command:

composer require laravel/ui


Now, execute the below command on the terminal for creating login, registration, forget password and reset password blade files:

php artisan ui bootstrap --auth


Then execute the following commands:

npm install
npm run dev
Step 4: Create Middleware And Setting Up

In this laravel multi auth system, create a middleware for checking the users. Who can access the admin area or who can access the normal user area?

php artisan make:middleware IsAdmin


After creating a middleware go-to app/Http/middleware. Implement the logic here for checking a logged-in user. Update the code in this handle function.

<?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.");
    }
}

Then register this middleware in the app/Http/Kernel.php. So, open kernal.php and add the following $routeMiddleware property in it:

....
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 5: Define Route

Create routes and add them to the web.php file as below.

Open routes/web.php file

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\HomeController;

Route::get('admin/home', [HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');
Step 6: Create Methods In Controller

open the HomeController.php file, which is placed on app/Http/Controllers/ directory. Then add the following code into it:

<?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 7: Create Blade View

create two-blade view files first is display home page and the second is display after login.

Open the resources/views/home.blade. file and update the below code.

@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">
                    @if(auth()->user()->is_admin == 1)
                    <a href="{{url('admin/routes')}}">Admin</a>
                    @else
                    <div class=”panel-heading”>Normal User</div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

I checked the user profile. If it is admin, it will navigate to the admin area. Otherwise, it will redirect to user's area.

Create admin.blade.php file inside resources/views/ directory and update the following code:

@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">
                    @if(auth()->user()->is_admin == 1)
                    <a href="{{url('admin/routes')}}">Admin</a>
                    @else
                    <div class=”panel-heading”>Normal User</div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
Step 8: Run Development Server

Start the development server using the below command and test our laravel 8 multi auth system:

php artisan serve

I hope it can help you...

  1. Hey Ajay, thank you for this clean tutorial. I have once an year a laravel project and i woundering why laravel change in every update the auth conditions. It is a big mess. In your tutorial i found a good solution for multiple auth. what do you think about two seperates login/reg forms. one for the users and one for the admins. whit their own routes? it is possible to change your way on easy way? i will try. if you like i will publish my result in your comments...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close