Laravel 8 Multi Authentication Example Tutorial

Laravel 8 multi (auth) authentication example tutorial. In this tutorial, you will learn how to create multi auth system in laravel 8.

Note that, Multiple auth system means multiple users can log in one application according to roles. Multiple authentications are very important in the large application of laravel. Authentication is the process of recognizing user credentials.

Laravel 8 multi auth system, create a middleware for checking the user’s role. It is an admin or normal user. Then create middleware name isAdmin and configuration in the kernal.php file and also in the route file.

Laravel 8 Multi Auth: Create Multiple Authentication in Laravel

  • Step 1: Install Laravel 8 App
  • Step 2: Connecting App to Database
  • Step 3: Setting up migration and model
  • Step 4: Create Middleware and Setting up
  • Step 5: Define Route
  • Step 6: Create Methods in Controller
  • Step 7: Create Blade View
  • Step 8: Start Development Server

Step 1: Install Laravel 8 App

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

composer create-project --prefer-dist laravel/laravel LaraMulti

Step 2: Connecting App to Database

After successfully download 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

3. Setting up migration and model

Next, add is_admin column in the users table using mirgration 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',
    ];
}

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

php artisan migrate

Now, create a build-in authentication system. Use the below command for creating the default auth system in laravel. And change laravel build-in auth system to multi auth system

This command will create routes, controllers and views files for Laravel Login Authentication and registration. It means to provide a basic laravel login authentication and registration Complete system. Let’s 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 
 composer laravel ui

Now, execute the below command on 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 users. 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 it on web.php file as like 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

Now 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

Now, create two blade view files first is display home page and 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

Now, I checked the user profile. If it is admin, it will navigate to the admin area. Otherwise, it will redirect to users 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

Now, start the development server using the below command and test our laravel 8 multi auth system:

php artisan serve

After complete all steps, see the last testing steps for laravel multi auth system :

  • First, register a user through the Laravel register.
  • Second Change the status is_admin = 1 in users table
  • Third Login into a laravel application

Recommended Laravel Posts

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Laravel 8 Multi Authentication Example Tutorial

  1. Perfect!

Leave a Reply

Your email address will not be published. Required fields are marked *