PHPackages                             ipregistry/ipregistry-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. ipregistry/ipregistry-laravel

ActiveLibrary[API Development](/categories/api)

ipregistry/ipregistry-laravel
=============================

Official Laravel integration for the Ipregistry IP geolocation and threat data API.

v1.0.0(3d ago)00Apache-2.0PHP &gt;=8.2

Since Jul 7Compare

[ Source](https://github.com/ipregistry/ipregistry-laravel)[ Packagist](https://packagist.org/packages/ipregistry/ipregistry-laravel)[ Docs](https://ipregistry.co)[ RSS](/packages/ipregistry-ipregistry-laravel/feed)WikiDiscussions Synced today

READMEChangelog (1)Dependencies (11)Versions (2)Used By (0)

[![Ipregistry](https://camo.githubusercontent.com/6351676fbebd87b54ff50f3b2fae63bc9bdb30471cf42a5e15b8a0407872124c/68747470733a2f2f63646e2e697072656769737472792e636f2f69636f6e732f66617669636f6e2d39367839362e706e67)](https://ipregistry.co/)

Ipregistry Laravel Library
==========================

[](#ipregistry-laravel-library)

[![License](https://camo.githubusercontent.com/55252c8bdb8cce91195de72acc8ada6436f3ce1971d3e113bf281cf411acbfd7/687474703a2f2f696d672e736869656c64732e696f2f3a6c6963656e73652d6170616368652d626c75652e737667)](LICENSE)[![Packagist Version](https://camo.githubusercontent.com/b44c18d08634d10bc6445369054a8ff636b875f38762afbc900c8d9d03ff50ba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f697072656769737472792f697072656769737472792d6c61726176656c)](https://packagist.org/packages/ipregistry/ipregistry-laravel)[![CI](https://github.com/ipregistry/ipregistry-laravel/actions/workflows/ci.yml/badge.svg)](https://github.com/ipregistry/ipregistry-laravel/actions/workflows/ci.yml)[![Lint](https://github.com/ipregistry/ipregistry-laravel/actions/workflows/lint.yml/badge.svg)](https://github.com/ipregistry/ipregistry-laravel/actions/workflows/lint.yml)

This is the official Laravel integration for the [Ipregistry](https://ipregistry.co) IP geolocation and threat data API. It is built on top of the official [`ipregistry/ipregistry-php`](https://github.com/ipregistry/ipregistry-php) client library and makes it feel native to Laravel: auto-discovered configuration, a facade, a request macro, route middleware for country and threat blocking, Laravel cache integration, a first-class testing fake, and an artisan command.

```
Route::get('/welcome', function (Request $request) {
    return 'Hello ' . ($request->ipregistry()?->location->country->name ?? 'visitor') . '!';
});
```

Features
--------

[](#features)

- **One call anywhere**: `$request->ipregistry()` returns the visitor's data from any controller, form request, or view. The API is queried at most once per request.
- **Route middleware**: enrich requests, block countries (`ipregistry.countries:block,KP,IR`), and block threats, proxies, Tor, or VPNs (`ipregistry.threats:tor,vpn`) with one line.
- **Laravel caching**: lookups are memoized in any of your configured cache stores (Redis, Valkey, Memcached, and so on), so repeated visits from the same IP do not consume additional credits.
- **GDPR helper**: `Ipregistry::isEu()` based on the API's `location.in_eu` field.
- **Safe by default**: fails open when Ipregistry is unreachable, honors your trusted proxy configuration, and never sends private IP addresses to the API.
- **Testable**: `Ipregistry::fake()` swaps the service for a fake with canned responses and assertions. No HTTP, no credits.
- **Batteries included**: `php artisan ipregistry:lookup 8.8.8.8` and `php artisan about` integration.

Getting started
---------------

[](#getting-started)

You need an Ipregistry API key. Sign up at  to get one along with free lookups.

### Requirements

[](#requirements)

- PHP 8.2 or newer (8.3+ for Laravel 13)
- Laravel 12 or 13

### Installation

[](#installation)

```
composer require ipregistry/ipregistry-laravel
```

Add your API key to `.env`:

```
IPREGISTRY_API_KEY=YOUR_API_KEY
```

That's it. The service provider is auto-discovered. Optionally publish the configuration file:

```
php artisan vendor:publish --tag=ipregistry-config
```

### Quick start

[](#quick-start)

Read the visitor's data anywhere you have the request. The lookup runs lazily on first access, is cached, and returns `null` instead of throwing when the visitor IP is private (localhost) or Ipregistry is unreachable:

```
Route::get('/welcome', function (Request $request) {
    $info = $request->ipregistry(); // ?IpInfo

    return view('welcome', [
        'country' => $info?->location->country->name,
        'city' => $info?->location->city,
        'currency' => $info?->currency->code,
    ]);
});
```

Or use the facade for explicit lookups. These throw on failure, like the underlying client:

```
use Ipregistry\Laravel\Facades\Ipregistry;

$info = Ipregistry::lookup('54.85.132.205');
$list = Ipregistry::lookupBatch(['8.8.8.8', '1.1.1.1']);
$origin = Ipregistry::lookupOrigin();                 // your server's own IP
$agents = Ipregistry::parseUserAgents($userAgent);

Ipregistry::forRequest($request);                     // same as $request->ipregistry()
```

Dependency injection works too: type-hint `Ipregistry\Laravel\Ipregistry`, or the raw `Ipregistry\IpregistryClient` for direct SDK access.

Middleware
----------

[](#middleware)

### Enriching requests

[](#enriching-requests)

The `ipregistry` middleware performs the lookup before your handlers run. Middleware parameters select the response fields for the route, keeping responses small and fast:

```
use Ipregistry\Laravel\Http\Middleware\EnrichWithIpregistry;

Route::middleware(EnrichWithIpregistry::using('ip', 'location', 'security'))->group(function () {
    // $request->ipregistry() answers from memory in here.
});

// Equivalent alias syntax:
Route::middleware('ipregistry:ip,location,security')->group(...);
```

The middleware is optional: `$request->ipregistry()` triggers the lookup lazily wherever it is first called. Use the middleware when you want the data fetched up front, a per-route field selection, or fail-closed behavior.

### Blocking countries

[](#blocking-countries)

Respond with `451 Unavailable For Legal Reasons` by ISO 3166-1 alpha-2 country code:

```
use Ipregistry\Laravel\Http\Middleware\BlockCountries;

// Block visitors from the listed countries:
Route::middleware(BlockCountries::block('KP', 'IR'))->group(...);

// Or only allow visitors from the listed countries:
Route::middleware(BlockCountries::allow('FR', 'BE'))->group(...);

// Equivalent alias syntax:
Route::middleware('ipregistry.countries:block,KP,IR')->group(...);
```

The static builders validate the country codes at route-definition time, so a typo fails fast instead of silently never matching.

### Blocking proxies, Tor, and threats

[](#blocking-proxies-tor-and-threats)

Respond with `403 Forbidden` to visitors flagged by Ipregistry security data. The `is_threat`, `is_attacker`, and `is_abuser` signals are always blocked; anonymization signals are opt-in:

```
use Ipregistry\Laravel\Http\Middleware\BlockThreats;

// Threats, attackers, and abusers:
Route::middleware(BlockThreats::including())->group(...);

// Additionally block proxies, Tor, and VPNs:
Route::middleware(BlockThreats::including('proxy', 'tor', 'vpn'))->group(...);

// Equivalent alias syntax:
Route::middleware('ipregistry.threats:proxy,tor,vpn')->group(...);
```

Accepted signals: `proxy`, `tor`, `vpn`, `relay`, `anonymous`. Each maps to the same-named `security.is_*` field of the Ipregistry response (`tor` also covers `is_tor_exit`).

### Fail open, fail closed

[](#fail-open-fail-closed)

All middleware fail open by default: when the country or threat status could not be determined (private IP, timeout, API error), the visitor is let through and the failure is reported to your exception handler. An Ipregistry outage never locks users out.

For security-sensitive apps that must not serve traffic without IP intelligence, set `IPREGISTRY_FAIL_OPEN=false` (or `'fail_open' => false`): the `ipregistry` middleware then responds with 503 when a lookup fails.

Ad-hoc decisions stay plain Laravel, no special API needed:

```
if ($request->ipregistry()?->security->isTor) {
    abort(403, 'Not available over Tor.');
}
```

GDPR and EU detection
---------------------

[](#gdpr-and-eu-detection)

```
use Ipregistry\Laravel\Facades\Ipregistry;

if (Ipregistry::isEu($request)) {
    // Show the cookie consent banner.
}

// Default to showing consent UIs when the data is missing:
Ipregistry::isEu($request, assumeEu: true);
```

`isThreat()` and `isBot()` follow the same pattern and also accept an `IpInfo` or nothing (current request):

```
Ipregistry::isThreat($request, tor: true, vpn: true);
Ipregistry::isBot($request);   // lightweight User-Agent heuristic, no API call
```

Configuration
-------------

[](#configuration)

Everything is configured in `config/ipregistry.php`, backed by environment variables:

OptionEnvironment variableDefaultDescription`api_key``IPREGISTRY_API_KEY`NoneYour Ipregistry API key.`base_url``IPREGISTRY_BASE_URL`default endpointAPI endpoint; `eu` selects the EU-based endpoint, or set a full URL.`cache.enabled``IPREGISTRY_CACHE_ENABLED``true`Cache successful lookups.`cache.store``IPREGISTRY_CACHE_STORE`default storeAny store from `config/cache.php`.`cache.ttl``IPREGISTRY_CACHE_TTL``600`Cache lifetime in seconds.`development_ip``IPREGISTRY_DEVELOPMENT_IP`NoneFixed public IP used when the client IP is private (localhost).`fail_open``IPREGISTRY_FAIL_OPEN``true`Let requests through when lookups fail.`fields``IPREGISTRY_FIELDS`full responseDefault field selection for all lookups, e.g. `ip,location,security`.`hostname``IPREGISTRY_HOSTNAME``false`Resolve reverse-DNS hostnames.`retries.max``IPREGISTRY_RETRIES``1`Automatic retries; kept low so failures never stall page loads.`timeout``IPREGISTRY_TIMEOUT``5`Per-request timeout in seconds.> Tip: set `IPREGISTRY_FIELDS` to fetch only what you use, keeping payloads small and lookups fast. For example, `ip,location,security` covers geo features, blocking, and GDPR detection.

`php artisan about` shows the effective configuration at a glance.

### Client IP and trusted proxies

[](#client-ip-and-trusted-proxies)

The visitor IP comes from `$request->ip()`, so it honors Laravel's [trusted proxy configuration](https://laravel.com/docs/requests#configuring-trusted-proxies). Behind a load balancer or CDN, configure your trusted proxies (e.g. in `bootstrap/app.php`), otherwise the extracted IP will be your proxy's, not your visitor's:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->trustProxies(at: '10.0.0.0/8');
})
```

Private and reserved addresses are never sent to the API. On localhost that means `$request->ipregistry()` returns `null`. Set a development IP to exercise geo features:

```
# .env (local only)
IPREGISTRY_DEVELOPMENT_IP=66.165.2.7
```

### Caching

[](#caching)

Successful lookups are stored in the configured Laravel cache store with a 10-minute lifetime by default, keyed by IP and lookup options. With Redis or Valkey the cache is shared across workers and deploys. Within a single request the result is additionally memoized on the request object, so middleware, guards, controllers, and views share one lookup.

### Laravel Octane

[](#laravel-octane)

The package is Octane-friendly: the client and service are stateless singletons, and per-visitor data is attached to the request instance, never to shared state.

Testing
-------

[](#testing)

Call `Ipregistry::fake()` in your tests to replace the service with a fake. No HTTP request is ever sent, and lookups are recorded for assertions:

```
use Ipregistry\Laravel\Facades\Ipregistry;

public function test_eu_visitors_see_consent_banner(): void
{
    Ipregistry::fake([
        '*' => ['location' => ['country' => ['code' => 'FR'], 'in_eu' => true]],
    ]);

    $this->get('/')->assertSee('cookie-consent');
}

public function test_tor_visitors_cannot_checkout(): void
{
    $fake = Ipregistry::fake([
        '1.2.3.4' => ['security' => ['is_tor' => true]],
    ]);

    $this->withServerVariables(['REMOTE_ADDR' => '1.2.3.4'])
        ->post('/checkout')
        ->assertForbidden();

    $fake->assertLookedUp('1.2.3.4');
}
```

Responses are keyed by IP address (`'*'` is the fallback, `'origin'` answers origin lookups) and use the API's payload shape; the `ip` key is filled in for you. Values can also be ready-made `IpInfo` instances, or `Throwable`s to simulate failures. Unlike the real service, the fake looks up private IPs too, so feature tests work without trusted-proxy setup.

Available assertions: `assertLookedUp()`, `assertNotLookedUp()`, `assertLookedUpTimes()`, `assertNothingLookedUp()`, `assertOriginLookedUp()`, `assertUserAgentsParsed()`, plus `lookups()` for the raw list.

Artisan command
---------------

[](#artisan-command)

Verify your key and inspect responses from the terminal:

```
php artisan ipregistry:lookup 8.8.8.8
php artisan ipregistry:lookup 8.8.8.8 1.1.1.1 --fields=location,security
php artisan ipregistry:lookup --hostname      # your server's own IP
```

Errors
------

[](#errors)

Explicit lookups (`Ipregistry::lookup()` and friends) throw the client library's exceptions: `ApiException` for API-reported failures (with typed `errorCode`) and `ClientException` for network errors. Both extend `IpregistryException`. See the [ipregistry-php error documentation](https://github.com/ipregistry/ipregistry-php#errors).

Request-aware helpers (`$request->ipregistry()`, `Ipregistry::forRequest()`, the middleware) never throw: failures are reported to your exception handler, `null` is returned, and the exception is available as `$request->attributes->get('ipregistry.error')`.

Migrating from `ipregistry/ipregistry-php`
------------------------------------------

[](#migrating-from-ipregistryipregistry-php)

Keep using the SDK directly for queue jobs and batch pipelines if you like; this package registers a ready-configured `Ipregistry\IpregistryClient` singleton you can inject. What the package adds on top: configuration, request-aware lookups with per-request memoization, IP extraction honoring trusted proxies, Laravel cache wiring, blocking middleware, and the testing fake.

Other resources
---------------

[](#other-resources)

- [API documentation](https://ipregistry.co/docs)
- [Issue tracker](https://github.com/ipregistry/ipregistry-laravel/issues)
- Email:

License
-------

[](#license)

Apache License 2.0. See [LICENSE](LICENSE).

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance99

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1c1794b460d8bc40a7ddeef8c1c0f2d4e03a85cab68f1001492aac3c5dd952ae?d=identicon)[ipregistry](/maintainers/ipregistry)

---

Tags

middlewarelaravelgeoipgeolocationIPip geolocationip-addressvpn detectionipregistryIP DataProxy detectionthreat-data

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ipregistry-ipregistry-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/ipregistry-ipregistry-laravel/health.svg)](https://phpackages.com/packages/ipregistry-ipregistry-laravel)
```

###  Alternatives

[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M134](/packages/laravel-pulse)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M167](/packages/laravel-mcp)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M133](/packages/roots-acorn)[propaganistas/laravel-disposable-email

Disposable email validator

6023.0M7](/packages/propaganistas-laravel-disposable-email)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M216](/packages/laravel-ai)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
