Categories: Blog

How To Restrict User Access From IP Address In Laravel

In Laravel, you can restrict user access from specific IP addresses by creating a middleware that checks the user’s IP address and denies access if it is on a blocked list.

Here are the steps to create a middleware to block access from specific IP addresses:

  1. Create a new middleware file by running the command php artisan make:middleware BlockIp
  2. In the newly created file, add a handle method that retrieves the user’s IP address and compares it to a list of blocked IP addresses.
  3. Add the middleware to the routes or controllers that you want to block access to.

Here is an example of what the handle method in the middleware file might look like

public function handle($request, Closure $next)
{
    $ip = $request->ip();
    $blockedIps = ['127.0.0.1', '192.168.0.1'];
    if (in_array($ip, $blockedIps)) {
        return response()->json(['error' => 'Access denied.'], 403);
    }
    return $next($request);
}

To add the middleware to a specific route or controller, you can use the middleware method. For example, if you want to add this middleware to a route group

Route::middleware(['auth','blockip'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index');
});

It will block access to the ‘/dashboard’ route for the IP addresses specified in the middleware

Anil Bajracharya

Developer,a tech enthusiastic who's passionate about learning new technology and programming Find me on linkedin linkedin

Recent Posts

Unveiling the Unforeseen: The Viral Journey of ‘Nothing Except Everything’ on YouTube

In September 2023, Wesley Wang uploaded a YouTube video titled "nothing except everything," which unexpectedly…

6 months ago

Alexia Tabone  Biography,Brand Ambassador, Age, Height, Weight,Lifestyle

Alexia Tabone is a highly respected neuroscientist known for her groundbreaking research in the field…

6 months ago

Bisket jatra highlight

भक्तपुरमा नौ दिन आठ रातसम्म परम्परागत विधिअनुसार मनाइने विश्वप्रसिद्ध बिस्का: जात्रा आज चैत २७ गते…

7 months ago

Viennese Jewish – The Woman Who Invented WI-FI

The Woman Who Invented WI-FI. The most beautiful woman in the world in cinema and…

10 months ago

Sadhguru Quotes in nepali

“यस क्षण” कुनै सोच होइन । यो एक मात्र वास्तविकता हो तपाईं आफूलाई अरूसँग तुलना…

10 months ago

how to check See result with marksheet

Dear SEE Students: तपाईंको नतिजाको Grading system यस्तो रहनेछ ! कुनै पनि विद्यार्थी फेल हुने…

1 year ago

This website uses cookies.