ItSolutionStuff.com

Laravel 11 Restrict User Access from IP Address Example

By Hardik Savani • September 4, 2024
Laravel

In this short article, we will learn how to restrict user access from ip address in laravel 11 application. we can create middleware to block user by ip address.

Sometimes, we want to restrict or block specific IP addresses from accessing our website. In this tutorial, I will show how to create middleware to block IP addresses from accessing URLs. By restricting access based on IP address, website owners can ensure that only authorized users are able to access their site or service. This is especially useful for websites or services that contain sensitive or confidential information, or that are targeted at a specific geographic region. To implement IP address restrictions, website owners can use a variety of tools and techniques, such as firewalls, access control lists, or web application firewalls. These tools can be configured to block access to a website or service from specific IP addresses or ranges of IP addresses, or to allow access only from certain trusted IP addresses.

In this tutorial example, we will create one middleware called "BlockIpMiddleware" and we will use that middleware on every secure API and URL. So the middleware will check the IP address against a given blacklist of IPs. Let's see the simple steps:

laravel 11 block ip address

Step for Laravel 11 Black List of User IP Address Example

  • Step 1: Install Laravel 11
  • Step 2: Create Middleware
  • Step 3: Register Middleware
  • Step 4: Use Middleware
  • Run Laravel App:
  • >

Step 1: Install Laravel 11

First of all, we need to get a fresh Laravel 11 version application using the command below because we are starting from scratch. So, open your terminal or command prompt and run the command below:

composer create-project laravel/laravel example-app

Step 2: Create Middleware

In this step, open the terminal and run the command below to create the BlockIpMiddleware middleware file. So, let's run the command below:

php artisan make:middleware BlockIpMiddleware

Now, it's created a new BlockIpMiddleware.php file. You have to add blocked IPs to the $blockIps array list. Let's update the following code in this file.

app/Http/Middleware/BlockIpMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BlockIpMiddleware
{
    public $blockIps = ['whitelist-ip-1', 'whitelist-ip-2', '127.0.0.1'];
  
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (in_array($request->ip(), $this->blockIps)) {
            abort(403, "You are restricted to access the site.");
        }
  
        return $next($request);
    }
}

Step 3: Register Middleware

In this file, we need to register middleware in the app.php file. We will call the blockIP middleware newly created. So let's update the following file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'blockIP' => \App\Http\Middleware\BlockIpMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Step 4: Use Middleware

In this step, we will create one route and show you how to use middleware in the route file. So let's open your route file and update the following code:

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\RSSFeedController;
use App\Http\Controllers\UserController;
    
Route::middleware(['blockIP'])->group(function () {
    Route::resource('users', UserController::class);
    Route::resource('rss', RSSFeedController::class);
});

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/users

You will find following layout:

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel 11 Livewire CRUD using Jetstream & Tailwind CSS

Read Now →

Laravel 11 Google Autocomplete Address Example

Read Now →

Laravel 11 Ajax Dependent Dropdown Example

Read Now →

How to Save JSON Data in Database in Laravel 11?

Read Now →

Setup Automatic Daily Database Backup with Laravel 11

Read Now →

Laravel 11 CRUD with Image Upload Tutorial

Read Now →

Laravel 11 Razorpay Payment Gateway Integration Example

Read Now →

How to Install and Configuration Telescope in Laravel 11?

Read Now →

Laravel 11 Google Recaptcha V3 Validation Tutorial

Read Now →

Laravel 11 Image Intervention Tutorial With Example

Read Now →

How to Create Event Calendar in Laravel 11?

Read Now →

Laravel 11 Summernote Image Upload Tutorial

Read Now →

How to use Multiple Database in Laravel 11?

Read Now →