Laravel Block IP Addresses from Accessing Website

In this article, we’re going to learn how to block IP address from accessing the Laravel application. Let’s get started:

Table of Contents

  1. Create a Middleware
  2. Register the Middleware
  3. Test

Create a Middleware

Run this command to create a middleware named class RestrictIpMiddleware:

php artisan make:middleware RestrictIpMiddleware

Go to app/Http/Middleware folder and open RestrictIpMiddleware.php file & paste this code:

RestrictIpMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;

class RestrictIpMiddleware
{
    // set IP addresses
    public $restrictIps = ['ip-addr-1', 'ip-addr-2', '127.0.0.1'];

    /**
     * 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->restrictIps)) {
            return response()->json(['message' => "You don't have permission to access this website."]);
        }

        return $next($request);
    }
}

We’re able to set many IPs to $restrictIps array.

Register the Middleware

We need to register the newly created middleware to the app/Http/Kernel.php. Open the file and register our middleware in $middlewareGroups array like this:

Kernel.php
protected $middlewareGroups = [
    'web' => [
        //--------------
        \App\Http\Middleware\RestrictIpMiddleware::class,
    ],

    'api' => [
        //--------------
    ],
];

So, our middleware will be checked on every web request.

Test

We’ve completed all the tasks. Let’s test by visiting our application from the restricted IP address. If everything is okay, you’ll see a message like:

{
    message: "You don't have permission to access this website."
}

That’s all. Thank you.