Restrict user based on IP address in laravel

This blog’s main objective is to build a functionality that can restrict or block users from accessing websites based on particular IP addresses.

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. We can do that by middleware in Laravel.

Create Restrict IP Middleware

In Laravel, middleware is a filtering mechanism that filters requests and responses. To create middleware open the terminal and enter the following command :

php artisan make:middleware RestrictIpAddress

This command will create a new file at App\Http\Controllers\RestrictIpAddress.php. Practically we will write all logic for IP Restriction into this file. So make the below changes :

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

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

Register Middleware in Kernel

In this last step, you need to register newly created middleware to your application. For that open In this last step, you need to register newly created middleware to your application. For that open App\Http\Kernel.php and make the following changes: and make the following changes :

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\RestrictIpAddress::class,// Add this line
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];
}

Testing Our Functionality

Now our functionality to restrict users based on their IP address is completed so you can test it. For testing, you have already added 127.0.0.1 to our blocked list. so run the application into localhost and it will raise an error.

php artisan serve

open below URL into your browser :

http://127.0.0.1:8000

Here, we defined IP address statically into our middleware but you can also use a database for that purpose.