Laravel Block IP Addresses from Accessing Website

Published on March 15, 2020 49 sec read

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:


namespace App\Http\Middleware;

use Closure;

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

     * 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:

protected $middlewareGroups = [
    'web' => [

    'api' => [

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


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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.