Laravel Restrict User Access from Specific IP Address

avatar
Published: Jan 25, 2023

Hello Artisans, today I'll show you how to restrict list of IP address form accessing your laravel application. For achieving our expected result, we just need to complete 2 steps. So, let's see how we can easily integrate an IP address blocker in our laravel application. 

Note: Tested on Laravel 9.19

Table of Contents

  1. Create and Setup Middleware
  2. Create Route
  3. Output

Create and Setup Middleware

First of all, we'll create a middleware so that we can define some IP's which we want to block and based on that we can restrict user or can give them access to our application. So, fire the below commands in the terminal to create a middleware.

php artisan make:middleware RestrictIpMiddleware

It'll create a middleware under app\Http\Middleware called RestrictIpMiddleware.php. Open the file and replace with below codes.

app/Http/Middleware/RestrictIpMiddleware.php
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Mail;

class SenMailController extends Controller
{
    public $block_ips = ['blacklist-ip-1', 'blacklist-ip-2', '127.0.0.1'];

    public function handle(Request $request, Closure $next)
    {
        if (in_array($request->ip(), $this->block_ips)) {
            return abort(403);
        }
        return $next($request);
    }
}

Now we need to register the middleware. Open kernel.php update the $routeMiddlleware array as following

app/Http/Kernel.php
protected $routeMiddleware = [


					.....
        'blockIp' => RestrictIpMiddleware::class
    ];

And our middleware is successfully registered. Now, if any user wants to access in our application it'll check, if the current IP is blacklisted or not.

Create Route

Now we'll create routes so that we can access in our view file. So, put the below route in web.php file.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

Route::middleware('blockIp')->get('/', function () {
    return view('welcome');
});

Output

And finally we're ready with our setup. It's time to check our output. Now go to http://127.0.0.1:8000, If everything goes well, we can find a below output.

That's it for today. I hope you've enjoyed this tutorial. You can also download this tutorial from GitHub. Thanks for reading. 🙂

Comments

No comments yet…