Build Laravel 6 Multiple Authentication Using Middleware in User Table

In this tutorial, I’m going to show you how to build Laravel Multiple Authentication Using Middleware in User Table. To verify users, applications need to have authentication functionality. I’ll how to authenticate an admin user and a normal user in the user table.

Table of Contents

Let’s see the steps:

  1. Install Laravel and Basic Configurations
  2. Configure User Table
  3. Make Auth and Middleware
  4. Configure the Middleware
  5. Protect Routes with Middleware

Step 1 : Install Laravel and Basic Configurations

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Step 2 : Configure User Table

Go to database/migrations, open the users_table migration file and add this line in the up() function:

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

Here’s the full example:

date_143915_create_users_table.php
<?php

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

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

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

Now migrate the table by entering this command:

php artisan migrate

Step 3 : Make Auth and Middleware

Laravel has a built-in authentication system for registration and login. Just run these commands:

Laravel 6:

# install laravel/ui package:
composer require laravel/ui --dev

# make auth
php artisan ui:auth

Laravel 5.8 or older:

php artisan make:auth

We have to create a middleware. Let’s create Admin middleware by this command:

php artisan make:middleware Admin

We have successfully created Auth and Middleware.

Step 4 : Configure the Middleware

Next, we have to configure the Admin middleware. Go to app/Http/Middleware/Admin.php and paste this whole code to the Admin.php:

app/Http/Middleware/Admin.php
<?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()->isAdmin == 1) {
            return $next($request);
        }

        return redirect('/')->with('error', 'You have not admin access.');
    }

}

To register this middleware, open app/Http/Kernel.php and this line to the routeMiddleware array in your kernel.php file:

app/Http/Kernel.php
/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    // --------------
    'admin' => \App\Http\Middleware\Admin::class,
];

Our Admin middleware is ready to use. ?

Step 5 : Protect Routes with Middleware

Let’s protect our routes with the middleware. Open the routes/web.php file and protect your routes with authentication using middleware like this:

routes/web.php
<?php

/*
|--------------------------------------------------------------------------
| 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!
|
*/

// open for all
Route::get('/', function () {
    return 'Welcome Everybody!';
});

// protect single route with authentication
Route::get('admin_dash', 'DashboardController@admin')->middleware('admin');

// protect group routes with authentication
Route::get('admin_area', ['middleware' => 'admin', function () {

    Route::get('test', function () {
        return 'Welcome Admin!';
    });

}]);

I hope this article will help you. ?


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.