Laravel 9 Restrict User Access From IP Address

Laravel 9 restrict or block user access from IP address; Through this tutorial, i am going to show you how to restrict or block a user by IP address for accessing the website in laravel 9 apps.

Laravel 9 Restrict User Access From IP Addresses Tutorial

Follow following steps to implement restrict or block user by ip address in laravel 9 app:

  • Install Laravel 9 App
  • Connecting App to Database
  • Create a Middleware
  • Register the Middleware

Step 1: Install Laravel 9 App

Run the below given command on command prompt to download fresh laravel setup:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Connecting App to Database

Go to your project root directory, find .env file and setup database credential as follow:

 DB_DATABASE=here your database name here
 DB_USERNAME=here database username here
 DB_PASSWORD=here database password here

Step 3: Create a Middleware

Run the following command to create a middleware named class BlockIpMiddleware:

php artisan make:middleware BlockIpMiddleware

Now, Go to app/Http/Middleware folder and open BlockIpMiddleware.php file. Then update the following code into your BlockIpMiddleware.php file:

namespace App\Http\Middleware;
use Closure;
class BlockIpMiddleware
    // set IP addresses
    public $blockIps = ['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->blockIps)) {
            return response()->json(['message' => "You don't have permission to access this website."]);
        return $next($request);

Step 4: Register the Middleware

To register the middleware, so go to app/Http/ and open Kernel.php file. And register middleware as follow:

protected $middlewareGroups = [
    'web' => [
    'api' => [


Llaravel block IP address example tutorial, you have learned how to block user by its IP address in laravel app.

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *