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

Bisket jatra highlight

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

1 month 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…

4 months ago

Sadhguru Quotes in nepali

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

4 months ago

how to check See result with marksheet

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

11 months ago

10 essential prompts to boost your

10 essential prompts to boost your productivity: 1. Summarize: "Summarize the text below into 500…

12 months ago

15 powerful ChatGPT prompts to save you 15 hours a week

15 powerful ChatGPT prompts to save you 15 hours a week: 1. Use the 80/20…

12 months ago

This website uses cookies.