How to Restrict or Block User Access via IP Address in Laravel 8

Last updated on by Digamber

Profound tutorial on how to block, refrain, or restrict user access from IP address in Laravel 8 application. Throughout this tutorial, you will understand the nitty-gritty of restricting a user from accessing the website through an IP address.

IP address blocking is a standard configuration of a network service that refrains individual requests from hosts with specific IP addresses. Nonetheless, this tutorial’s primary objective is to build a functionality that can restrict or block user access based on particular IP addresses in the laravel environment.

Laravel 8 Block User Access via IP Addresses Example

This laravel block users by ip address helps you achieve a task to build for preventing access by a disruptive address. You will learn how to create a custom laravel middleware to filer out user requests based on a particular IP address.

The custom middleware will strengthen the app to block bad or evil users’ requests from penetrating your laravel application. Ideally, the trusted users with authentic ip address will be able to access the app.

Let’s checkout how to block IP addresses from accessing laravel application step by step.

Create Laravel Application

First step starts with installing a fresh laravel application, however you need to configure composer tool in your local development system to evoke app installation:

composer create-project laravel/laravel laravel-block-ip-address-example --prefer-dist

Database Connection

In second step you have to land onto .env configuration file, likewise add your database details to make the database connection:

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

Create Block IP Middleware

Generically, middleware in Laravel is a filtering mechanism that works as a bridge between a request and a response. So, we have to create a new middleware which will be used for blocking access for specific IP address.

Open console, run the php artisan command to generate a new middleware:

php artisan make:middleware RestrictIpAddressMiddleware

Then, head over to app/Http/Middleware/RestrictIpAddressMiddleware.php configuration file and replace the entire code with the following code:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RestrictIpAddressMiddleware
{
    // Blocked IP addresses
    public $restrictedIp = ['192.168.0.1', '202.173.125.72', '192.168.0.3', '202.173.125.71'];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (in_array($request->ip(), $this->restrictedIp)) {
            return response()->json(['message' => "You are not allowed to access this site."]);
        }
        return $next($request);
    }     
}

Add Middleware in Kernel

In this last step, we have to define the RestrictIpAddressMiddleware class in the $middlewareGroups array within the app/Http/Kernel.php file:

protected $middlewareGroups = [
        'web' => [
            ...
            ...
            ...
            
            \App\Http\Middleware\RestrictIpAddressMiddleware::class,
        ],

        'api' => [
            'throttle:api',
            ...
        ],
    ];

Summary

The laravel block IP address tutorial is over; in this tutorial, we comprehended how to create middleware and register within the kernel config file to block certain user’s access based on particular IP addresses.