Laravel 9 Multi Auth (Authentication) Tutorial with Example

Throughout this Laravel 9 multi auth tutorial, you will learn how to create multiple auth (Authentication) in Laravel application using middleware.
In general, Authentication is the security process, and it indicates acknowledging the genuine user with proper account details.

Multiple auth system means multiple users can log in one application according to roles. Let’s see the step by step process to implement laravel multiple user authentication system according their roles.

Laravel Multiple Authentication Example

Here is the archetype of this tutorial, we will develop two users one is admin, and the other one is a regular user. Based on their roles, we will allow them to access in the app using middleware. Let us follow the laravel multiple authentication system steps using roles based user.

  • Step 1: Install Laravel Application
  • Step 2: Setup Database Connection
  • Step 3: Set Up Model and Migration
  • Step 4: Generate Auth Scaffolding
  • Step 5: Create IsAdmin Middleware
  • Step 6: Create Routes
  • Step 7: Configure Home Controller
  • Step 8: Configure Blade View
  • Step 9: Configure Login Controller
  • Step 10: Create Dummy Data using Seeder
  • Step 11: Run Laravel Multi Auth App & Test

Install Laravel App

First we need to download the new laravel application using the following command.

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

Now, go to the project directory.

cd laravel-multi-auth

Setup Database Connection

Establish a database connection, open .env file and define your database details it makes the consensus between laravel and database.

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

Set Up Model and Migration

We have to declare the new property, name it (‘is_admin’), and propel it into users’ table by running the migration.

Open your users migration database\migrations\2014_10_12_000000_create_users_table.php and put the another column on it.

<?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->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->boolean('is_admin')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

Now, get inside the app\Models\User.php file and add the newly created is_admin property.

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'is_admin'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}

Now the migration command to excute the users table.

php artisan migrate

Generate Auth Scaffolding

Install Laravel UI package

composer require laravel/ui

Now using the below command create the auth archetypes.

php artisan ui bootstrap --auth

Run following command to compile your fresh scaffolding.

npm install && npm run dev

Create IsAdmin Middleware

Theoretically, this is a foundation step of laravel multi auth system tutorial. To complete the imperatives, evoke the below command from your terminal window.

php artisan make:middleware IsAdmin

Open app/Http/middleware/IsAdmin.php and paste the following code.

<?php
namespace App\Http\Middleware;
use Closure;
class Admin
{
    /**
     * 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',"Only admin can access!");
    }
}

You have to define the Admin middleware in app/Http/Kernel.php file, so paste the following code inside of $routeMiddleware array.

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

Add Routes

Open routes/web.php file and put the below code on it.

<?php

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


Route::get('home', [HomeController::class, 'index'])->name('home');
Route::get('admin/home', [HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin');

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

Auth::routes();

Configure Home Controller

We have to incorporate the handleAdmin() method inside the HomeController class, open app/Http/Controllers/HomeController.php, and add the following code.

<?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('admin-home');
    }
}

Configure Blade View

Open the pre-defined resources/views/home.blade.php file and insert the foundation code inside the file.

@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(session('login-success'))
                        <div class="alert alert-success" role="alert">
                            {{ session('login-success') }}
                        </div>
                    @endif
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    You are normal user.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Create and open resources/views/admin-home.blade.php file and add the 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(session('login-success'))
                        <div class="alert alert-success" role="alert">
                            {{ session('login-success') }}
                        </div>
                    @endif
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    You are admin.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Configure Login Controller

In this step we will configure LoginController class, define the login() method and insert the following code. It handles the server-side validation, redirects to admin dashboard if the logged in user is admin.

Incorporate the following code in app/Http/Controllers/Auth/LoginController.php file

<?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 = RouteServiceProvider::HOME;

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

    public function login(Request $request)
    {
        $request->validate([
            'email'     => 'required|email',
            'password'  => 'required'
        ]);

        $credentials = $request->only('email', 'password');

        if(! auth()->attempt($credentials)){
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }

        if (auth()->user()->is_admin == 1) {
            return redirect()->route('admin.home');
        }

        return redirect()->route('home');
    }
}

Create Dummy Data using Seeder

So create a userseeder using the following command:

php artisan make:seeder UsersSeeder

Now, open the database/seeds/UsersSeeder.php file and insert the following data.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class UsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $usersData = [
            [
               'name'   =>'Admin',
               'email'  =>'admin@example.com',
               'is_admin' => 1,
               'password' => Hash::make('12345678')
            ],
            [
               'name'       => 'User',
               'email'      => 'user@example.com',
               'is_admin'   => 0,
               'password'   => Hash::make('12345678')
            ],
        ];

        foreach ($usersData as $key => $val) {
            User::create($val);
        }
    }
}

Run Laravel Multi Auth App & Test

Evoke the laravel multi auth application with the given below command.

php artisan serve

Open the following URL on your browser on: http://127.0.0.1:8000/login

Admin Dashboard:

Use the below credentials for admin dashboard:

Email: admin@example.com
Password: 12345678

Here this view you will see after login using admin role

User Dashboard:

Use the below credentials for admin dashboard:

Email: user@example.com
Password: 12345678

Here this view you will see after login using normal user login

I hope you liked laravel multi auth tutorial step by step. So, don’t forget to share it with others, have a good day.

Leave a Comment