Here, we will block users from specific IP addresses from accessing our application. Let's assume you already have a working Laravel application. If not create a fresh Laravel application and configure the database.
To restrict users based on the IP address we need to check every request coming from the user against the database. We can simply do this by creating custom middleware.
Before starting we need to create a table to store blocked IP addresses and we will use this model to store blocked IPs and check against the requested IP address.
Create a Blocked IP Address Model and Migration
For this example, we need to create a model that stores all blocked IP addresses for that enter the below command into your terminal :
In this command, we have passed multiple parameters mfs while creating a model which will create migration, factory, and seeder. These additional files will be used for seeding data into our model.
Let's make changes in all files one by one.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBlockedIpsTable extends Migration
{
public function up()
{
Schema::create('blocked_ips', function (Blueprint $table) {
$table->id();
$table->ipAddress('ip'); //add this line
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('blocked_ips');
}
}
Now, we have to migrate our database. Enter the below command into a terminal :
Let's migrate this migration file and create a table in our database.
The above command will also generate a model factory and seeder. Let's modify it to seed some dummy data into it.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class BlockedIpFactory extends Factory
{
public function definition()
{
return [
'ip' => $this->faker->ipv4(),
];
}
}
<?php
namespace Database\Seeders;
use App\Models\BlockedIp; //add
use Illuminate\Database\Seeder;
class BlockedIpSeeder extends Seeder
{
public function run()
{
$blockedIps = BlockedIp::factory()->count(10)->create(); //add
}
}
This alteration will apply logic for creating 10 dummy addresses while you run the below command.
Create Restrict IP Middleware
In Laravel, middleware is a filtering mechanism that filters requests and responses. For creating middleware open the terminal and enter the following command :