IP location data is useful when your Laravel application needs a sensible regional default, timezone context, analytics enrichment, or an additional risk signal. The integration does not need a large package or a complicated SDK.

With IPRout, you can send an IPv4 or IPv6 address to a simple HTTP endpoint and receive GeoIP and network information as JSON. In this tutorial, we will get a seven-day developer key, keep it outside the codebase, and build a reusable Laravel service around the API.

GeoIP is an estimate derived from an IP address. It is not GPS data, proof of identity, or a user's exact physical location. Give users a way to correct important location-dependent choices.

What we are building

We will add an endpoint to a Laravel application that accepts an IP address:

GET /geoip?ip=8.8.8.8

The application will validate the input, ask IPRout for the IP context, and return a response containing fields such as:

  • Country, region, and city
  • Timezone
  • Latitude and longitude
  • Autonomous system number (ASN)
  • Network organisation

No third-party PHP package is required. Laravel's built-in HTTP client handles the request.

Get a seven-day IPRout developer key

IPRout provides a developer key for evaluating the API without creating an account. At the time of writing, the key:

  • Is valid for seven days
  • Includes 1,000 requests in total
  • Does not require a login

To generate one:

  1. Open the IPRout developer-key page.
  2. Select Generate API Key.
  3. Copy the generated key and store it somewhere secure.

Treat the key like a password. Do not publish it in a DEV post, commit it to Git, expose it in browser-side JavaScript, or write it to application logs.

The developer-key allowance and terms may change, so check the page for the current details before publishing or following this tutorial.

Configure Laravel

Add the key and API base URL to your project's .env file:

IPROUT_API_KEY=replace_with_your_key
IPROUT_API_BASE_URL=https://api.iprout.com

Next, add an IPRout entry to config/services.php:

'iprout' => [
    'key' => env('IPROUT_API_KEY'),
    'base_url' => env('IPROUT_API_BASE_URL', 'https://api.iprout.com'),
],

Using Laravel's configuration layer keeps calls to env() out of application code and works correctly when configuration is cached in production.

If you already cached your configuration, refresh it after changing .env:

php artisan config:clear

Create a reusable IPRout service

Create app/Services/IPRout.php:

<?php

namespace App\Services;

use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use InvalidArgumentException;
use RuntimeException;

class IPRout
{
    /**
     * Look up GeoIP and ASN information for an IPv4 or IPv6 address.
     *
     * @return array<string, mixed>
     */
    public function lookup(string $ip): array
    {
        if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
            throw new InvalidArgumentException('A valid IPv4 or IPv6 address is required.');
        }

        $apiKey = config('services.iprout.key');

        if (! is_string($apiKey) || $apiKey === '') {
            throw new RuntimeException('The IPRout API key is not configured.');
        }

        $response = Http::baseUrl(config('services.iprout.base_url'))
            ->withToken($apiKey)
            ->acceptJson()
            ->timeout(5)
            ->get('/ip/'.rawurlencode($ip));

        $this->ensureRequestSucceeded($response);

        return $response->json();
    }

    private function ensureRequestSucceeded(Response $response): void
    {
        if ($response->successful()) {
            return;
        }

        $message = match ($response->status()) {
            401 => 'The IPRout API key is missing or invalid.',
            422 => 'IPRout rejected the IP address as invalid.',
            429 => 'The IPRout request limit has been reached.',
            500 => 'IPRout encountered an internal server error.',
            default => 'The IPRout lookup failed with HTTP '.$response->status().'.',
        };

        throw new RuntimeException($message);
    }
}

The API also supports the X-API-Key header, but Laravel's withToken() method makes bearer authentication especially readable:

Authorization: Bearer YOUR_API_KEY

The five-second timeout prevents a slow external request from occupying an application worker indefinitely. Choose a production timeout and fallback based on your own request budget.

Add a controller

Generate a controller:

php artisan make:controller GeoIPController

Replace its contents with:

<?php

namespace App\Http\Controllers;

use App\Services\IPRout;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GeoIPController extends Controller
{
    public function __invoke(Request $request, IPRout $iprout): JsonResponse
    {
        $validated = $request->validate([
            'ip' => ['required', 'ip'],
        ]);

        return response()->json(
            $iprout->lookup($validated['ip'])
        );
    }
}

Laravel's service container can construct the IPRout class automatically, so no manual binding is needed for this service.

Register the route

Add the route to routes/web.php:

use App\Http\Controllers\GeoIPController;
use Illuminate\Support\Facades\Route;

Route::get('/geoip', GeoIPController::class);

Start the local development server:

php artisan serve

Then make a lookup from another terminal:

curl "http://127.0.0.1:8000/geoip?ip=8.8.8.8"

A successful response follows this shape:

{
  "ip": "8.8.8.8",
  "country_code": "US",
  "country": "United States",
  "region": "California",
  "city": "Mountain View",
  "timezone": "America/Los_Angeles",
  "latitude": 37.4056,
  "longitude": -122.0775,
  "asn": 15169,
  "organization": "Google LLC"
}

IP allocation and GeoIP datasets change, so do not write tests that require a public IP to return one permanent city or coordinate.

Look up the caller IP instead

IPRout also provides GET /ip, which returns information for the IP address making the API request. That is different from looking up the end user's address from your Laravel request.

In many deployments, IPRout will see the outbound IP of your application server when you call GET /ip. If you need information about a visitor, obtain the visitor IP through Laravel and pass it to GET /ip/{ip}.

Be careful when your application runs behind a reverse proxy or load balancer. Only trust forwarded IP headers when Laravel is configured with the proxies you control. Otherwise, a client may be able to supply a false header value.

Handle failure without breaking the application

An external lookup should not become a single point of failure. Decide what your application will do when the lookup is unavailable:

  • Use a neutral default for optional personalisation.
  • Record an analytics event without the enrichment fields.
  • Ask the user to select their region or timezone.
  • Require another risk signal instead of making an automatic security decision.

The documented IPRout error statuses are:

Status Meaning
401 Missing or invalid API key
422 Invalid IP address
429 Rate limited
500 Internal server error

Do not retry 401 or 422 responses without correcting the request. A limited retry with backoff may be appropriate for a transient server error, but retries must stay within your latency and request limits.

Production checklist

Before deploying the integration:

  • Keep IPROUT_API_KEY in your hosting platform's secret store.
  • Validate every supplied IP address.
  • Configure a short timeout and an application-specific fallback.
  • Avoid logging API keys or unnecessary raw IP addresses.
  • Review how long your application retains IP-derived data.
  • Cache repeated lookups only if that behaviour fits your data-freshness and privacy requirements.
  • Monitor 401, 422, 429, and server-error responses.
  • Let users correct important regional or timezone defaults.

Start your first Laravel GeoIP lookup

You now have a small Laravel integration with secure configuration, input validation, explicit error handling, and no additional package dependency.

Generate a seven-day IPRout developer key, then use the IPRout API documentation when you are ready to explore the complete request contract.