Laravel 10 Middleware Tutorial Example

Laravel Middleware is used to filter HTTP requests in your web application. One of the basic requirements of any web application is an HTTP requests filter, so we have to make one as well for example make auth middleware. auth middleware always checks if you are going then and then you can access those pages. in short term filter HTTP requests.

Step 1: Install Laravel

composer create-project laravel/laravel example-app

Step 2: Create Middleware

php artisan make:middleware IsActive

app/Http/Middleware/IsActive.php

<?php
   
   namespace App\Http\Middleware;
     
   use Closure;
   use Illuminate\Http\Request;
   use Symfony\Component\HttpFoundation\Response;
     
   class IsActive
   {
       /**
        * Handle an incoming request.
        *
        * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
        */
       public function handle(Request $request, Closure $next): Response
       {
           if (!auth()->user()->is_active) {
               return response()->json('Your account is inactive');
           }
     
           return $next($request);
       }
   }

Step 3: Register Middleware

app/Http/Kernel.php 

<?php
  
  namespace App\Http;
    
  use Illuminate\Foundation\Http\Kernel as HttpKernel;
    
  class Kernel extends HttpKernel
  {
      ....
    
      /**
       * The application's route middleware.
       *
       * These middleware may be assigned to groups or used individually.
       *
       * @var array
       */
      protected $routeMiddleware = [
          ....
          'is-active' => \App\Http\Middleware\IsActive::class,
      ];
  }

Step 4: Use Middleware

routes/web.php 

<?php
  
    use Illuminate\Support\Facades\Route;
      
    use App\Http\Controllers\RSSFeedController;
       
    /*
    |--------------------------------------------------------------------------
    | 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('/test-user', [App\Http\Controllers\HomeController::class, 'index'])->middleware(['auth', 'is-active']);

Step 5: Create Auth Scaffolding

composer require laravel/ui

Here, we need to generate auth scaffolding in laravel 10 using laravel ui command. so, let's generate it by bellow command:

php artisan ui bootstrap --auth

Now you need to run npm command, otherwise you can not see better layout of login and register page.

Install NPM:

npm install

Run NPM:

npm run dev

Step 6: Add  Column

we will create new migration to add is_active column

php artisan make:migration add_is_active_column

database/migrations/add_is_active_column.php

<?php
  
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
      
    return new class extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up(): void
        {
            Schema::table('users', function (Blueprint $table) {
                $table->boolean('is_active')->default(0);
            });
        }
      
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down(): void
        {
              
        }
    };

Run migration using below command:

php artisan migrate

update is_active column fillable property in model

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

Step 7: Create Seeder

php artisan make:seeder UserSeeder

Register UserSeeder in DatabaseSeeder.php

<?php
    namespace Database\Seeders;
    use Illuminate\Database\Seeder;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Seed the application's database.
         *
         * @return void
         */
        public function run()
        {
        
            $this->call(UserSeeder::class);
        }
    }
    

For Creating Record add below code in UserSeeder:

database/seeders/UserSeeder.php

<?php
  
    namespace Database\Seeders;
      
    use Illuminate\Database\Console\Seeds\WithoutModelEvents;
    use Illuminate\Database\Seeder;
    use App\Models\User;
    use Illuminate\Support\Facades\Hash;
      
    class UserSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run(): void
        {
            User::create([
                "name" => "One",
                "email" => "one@gmail.com",
                "password" => Hash::make("123456"),
                "is_active" => 1
            ]);
      
            User::create([
                "name" => "Two",
                "email" => "two@gmail.com",
                "password" => Hash::make("123456"),
                "is_active" => 0
            ]);
        }
    }
Run the Seeder,
php artisan db:seed --class=UserSeeder

Run Laravel App:

php artisan serve

Now, Go to web browser, type the given URL and see the output:

http://localhost:8000/login

login credentials with InActive User:

Email: two@gmail.com
Password: 123456

After login you have to go to the following URL:

http://localhost:8000/test-user