Home Laravel How To Create Middleware In Laravel 9 ?

How To Create Middleware In Laravel 9 ?

by Shahriar Sagor

Hello Dev , Today now in this post i will show you an example of laravel 9 middleware example. Here I would like to show you laravel 9 custom middleware example. From here you’ll learn how to create custom middleware in laravel 9. So here i will help you to give an example of how to use middleware in laravel 9.

Step 1: Install Laravel

At first of all we have to get the fresh Laravel version application by using the bellow command. So open your terminal OR command prompt and then run the bellow command:

composer create-project laravel/laravel example-app
Step 2: Create Middleware

Now in this step, need to open terminal and run the below command to create custom middleware file, So let’s run the below command:

php artisan make:middleware IsActive

Now, it’s created a new IsActive.php file. So let’s update the following code on this file.

app/Http/Middleware/IsActive.php

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

Step 3: Register Middleware

In this file, i have to register middleware on Kernel.php file. i will call is-active of new created middleware. So let’s update the following file.

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

Now in this step, i will create one route and then show you how to use the middleware in route file. So let’s open our route file and update the following code:

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

Here, i will create the auth scaffolding so, user can login and check the below url. So let’s install the laravel ui package and generate auth scaffolding.

First i have to install the laravel/ui package as like bellow:

composer require laravel/ui

Here, i have to generate the auth scaffolding in laravel 9 by using the laravel ui command. So, let’s generate it by using the bellow command:

php artisan ui bootstrap --auth

Now i have to run npm command, otherwise we can not see the better layout of login and register page.

Install NPM:

npm install

Run NPM:

npm run dev
Step 6: Add is_active Column

Here, i will create the new migration to add is_active column in users table. So let’s create the migration and run it.

php artisan make:migration add_is_active_column

Next, simple i will update the below code to migration file.

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()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('is_active')->default(0);
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          
    }
};

Next, i need to run migration by using the below command:

php artisan migrate

Now, i will add is_active column in as fallible array of user model. So let’s update it.

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

Now in this step, i will create the UserSeeder to generate a active and inactive users default. So let’s create the seeder and create dummy in users to check.

php artisan make:seeder UserSeeder


And put the bellow code in UserSeeder seeder this way:

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()
    {
        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
        ]);
    }
}

After this i have to run the bellow command for run UserSeeder seeder:

php artisan db:seed --class=UserSeeder

Read Also: Laravel 9 Image Intervention Tutorial

Thanks for read. I hope it help you. For more you can follow us on facebook

For Source Code Middleware-In-Laravel-9

close

You may also like