PHPackages                             dive-be/laravel-geo - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. dive-be/laravel-geo

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

dive-be/laravel-geo
===================

Translate IP addresses into geo locations

1.5.0(1y ago)3711.0k↑19.2%3MITPHPPHP ~8.4CI passing

Since Apr 6Pushed 1y ago1 watchersCompare

[ Source](https://github.com/dive-be/laravel-geo)[ Packagist](https://packagist.org/packages/dive-be/laravel-geo)[ Docs](https://github.com/dive-be/laravel-geo)[ RSS](/packages/dive-be-laravel-geo/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (9)Dependencies (11)Versions (10)Used By (0)

[![Social Card of Laravel Dry Requests](https://github.com/dive-be/laravel-geo/raw/master/art/socialcard.png?raw=true)](https://github.com/dive-be/laravel-geo/blob/master/art/socialcard.png?raw=true)

🌍 - Translate IP addresses into geo locations
=============================================

[](#---translate-ip-addresses-into-geo-locations)

[![Latest Version on Packagist](https://camo.githubusercontent.com/f450cac2ff12282f3049e126705b176953a297caf41fc24a11a22659179e5dad/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f646976652d62652f6c61726176656c2d67656f2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dive-be/laravel-geo)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Total Downloads](https://camo.githubusercontent.com/da6d33ebb410965c6215fd2010fe575bfb18d86dca0916ce77b7a12f101a39b0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646976652d62652f6c61726176656c2d67656f2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dive-be/laravel-geo)

This package will assist you in grabbing a visitor's country.

What problem does this package solve?
-------------------------------------

[](#what-problem-does-this-package-solve)

Depending on the context of your application, you may want to display content tailored for a specific country/region of the visitor. This package will help with providing a sensible default using IP addresses if it is a first time visit for a user.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require dive-be/laravel-geo
```

You will also need to install GeoIP2 if you're planning to use their services:

```
composer require geoip2/geoip2
```

You can publish the config file with:

```
php artisan geo:install
```

This is the content of the config file:

```
return [
    /**
     * IP address translations can be cached to improve successive lookup times.
     */
    'cache' => [
        'enabled' => false,

        /**
         * Address translations are tagged to only clear them when a clear command is run.
         * Not supported by the "file", "database" and "dynamodb" cache drivers.
         */
        'tag' => 'dive-geo-location',

        /**
         * Time-to-live in seconds.
         */
        'ttl' => 3600,
    ],

    /**
     * Detectors are classes responsible for detecting the geo location of a given IP address.
     *
     * Supported drivers:
     *  - "static" (always translates to the fallback country)
     *  - "maxmind_db" (GeoIP2/GeoLite2 Databases)
     *  - "maxmind_web" (GeoIP2 Precision Web Services)
     *  - "ip2c" (IP 2 Country free web service)
     */
    'detectors' => [
        'driver' => env('GEO_DETECTORS_DRIVER', 'static'),

        'ip2c' => [
            'endpoint' => 'https://api.ip2country.info/ip',
        ],

        'maxmind_db' => [
            'database_path' => storage_path('app/geoip2.mmdb'),
            'license_key' => env('GEO_DETECTORS_MAXMIND_DB_LICENSE_KEY'),
            'url' => 'https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country&license_key=%s&suffix=tar.gz',
        ],

        'maxmind_web' => [
            'account_id' => env('GEO_DETECTORS_MAXMIND_WEB_ACCOUNT_ID'),
            'license_key' => env('GEO_DETECTORS_MAXMIND_WEB_LICENSE_KEY'),
        ],
    ],

    /**
     * A valid ISO alpha-2 country code.
     * Used when an IP address cannot be translated.
     */
    'fallback' => 'BE',

    'repos' => [
        'cookie' => [
            'name' => 'geo', // The cookie's name when set on the users' browsers
        ],
    ],

    /**
     * The valid FQCN of your custom transformer.
     * When set, values retrieved from the repository will be transformed first using this class.
     */
    'transformer' => null,
];
```

Usage
-----

[](#usage)

First, you will have to decide which service to use.

- [GeoIP2 Databases](https://www.maxmind.com/en/geoip2-databases)
- [GeoIP2 Precision Web Services](https://www.maxmind.com/en/geoip2-precision-services)
- [IP 2 Country](https://ip2country.info/)

### Detectors

[](#detectors)

When you've decided, set the `GEO_DETECTORS_DRIVER` environment variable to the correct value. Refer to the configuration file for the right values.

#### GeoIP2 Databases

[](#geoip2-databases)

- Generate a license key
- Set the `GEO_DETECTORS_MAXMIND_DB_LICENSE_KEY` environment variable to your license key

#### Auto updating local database

[](#auto-updating-local-database)

IP address ranges tend to become out of date over time. Therefore, this package also provides a convenient update command which you can schedule to run once a week to keep everything fresh.

```
// Console\Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->command('geo:update')->weekly();
}
```

Only applicable if using MaxMind's *GeoIP2 Databases*.

#### GeoIP2 Precision Web Services

[](#geoip2-precision-web-services)

- Get `account_id` &amp; `license_key`
- Set the `GEO_DETECTORS_MAXMIND_WEB_ACCOUNT_ID` &amp; `GEO_DETECTORS_MAXMIND_WEB_LICENSE_KEY` environment variables

#### IP 2 Country

[](#ip-2-country)

This is a free service. You don't have to configure anything.

> Note: it is strongly recommended to enable caching for this driver.

#### Static

[](#static)

The static driver is meant for usage during local development and testing. You should not use it in any other environment as it is always going to return the fallback value.

### Detecting a visitor's geo location

[](#detecting-a-visitors-geo-location)

Add the `DetectGeoLocation` (or alias `geo`) middleware to your kernel's `web` middleware stack and you are good to go. If your app is behind a proxy/load balancer, make sure `DetectGeoLocation` is defined **after** `TrustProxies`.

```
'web' => [
    // omitted for brevity
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Dive\Geo\Middleware\DetectGeoLocation::class,
],
```

Retrieving the detected country 🗺
---------------------------------

[](#retrieving-the-detected-country-)

There are multiple ways to retrieve the detected ISO alpha-2 country code.

#### Facade

[](#facade)

```
use Dive\Geo\Facades\Geo;

Geo::get();
```

or using the alias

```
use Geo;

Geo::get();
```

#### Helper

[](#helper)

```
geo()->get()
```

#### Dependency injection

[](#dependency-injection)

```
use Dive\Geo\Contracts\Repository;

public function __invoke(Repository $geo)
{
    $geo->get();
}
```

### Transforming the detected geo location 🔷

[](#transforming-the-detected-geo-location-)

It is a high probability that you'd like to transform the ISO alpha-2 country code into your own Eloquent model or value object after calling `get` on the repository class. You may define your own `CountryTransformer` which implements the `Transformer` interface and simply returns the desired object.

e.g.

```
namespace App\Transformers;

use App\Models\Country;
use Dive\Geo\Contracts\Transformer;

class CountryTransformer implements Transformer
{
    public function transform(string $iso): Country
    {
        return Country::findByIso($iso);
    }
}
```

After defining the class, make sure to provide the FQCN in the configuration file.

```
'transformer' => App\Transformers\CountryTransformer::class,
```

### Overwriting existing country ✍🏼

[](#overwriting-existing-country-)

At any point in time, you may overwrite the detected country code. Simply call:

```
geo('TR'); // helper
Geo::put('TR'); // facade
$geo->put('TR'); // injected
```

### Clearing the cache 🔥

[](#clearing-the-cache-)

When enabled, the translated addresses will be held in cache for a certain amount of time defined in the configuration file. If you'd like to wipe these translations, use the command:

```
php artisan geo:clear
```

> Note: the cache driver must support tagging or else **everything** will be cleared when the command above is run.

Extending the detectors 👣
-------------------------

[](#extending-the-detectors-)

If the default drivers do not fulfill your needs, you may extend the `DetectorManager` with your own custom drivers:

```
use Dive\Geo\Facades\Detector;

Detector::extend('ipapi', function () {
    return new IPApiDetector(...);
});
```

Testing 🔎
---------

[](#testing-)

This package offers fake implementations of the `Repository` &amp; `Detector` contracts so you can make assertions in your unit tests and make sure you ship that bug-free code 💪. Just call `fake` on either of them and you're set:

```
use Dive\Geo\Facades\Detector;
use Dive\Geo\Facades\Geo;

Detector::fake();
Geo::fake();
```

Testing (package)
-----------------

[](#testing-package)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Muhammed Sari](https://github.com/mabdullahsari)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance45

Moderate activity, may be stable

Popularity35

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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

Every ~186 days

Recently: every ~295 days

Total

9

Last Release

425d ago

Major Versions

0.2 → 1.02021-09-13

PHP version history (5 changes)0.1PHP ^8.0

1.2PHP ^8.1

1.3.0PHP ~8.2

1.4.0PHP ~8.3

1.5.0PHP ~8.4

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/59749?v=4)[Artem Loenko](/maintainers/dive)[@dive](https://github.com/dive)

---

Top Contributors

[![dive-michiel](https://avatars.githubusercontent.com/u/2650975?v=4)](https://github.com/dive-michiel "dive-michiel (1 commits)")

---

Tags

laravelisolocationgeodive

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/dive-be-laravel-geo/health.svg)

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

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[laravel/pulse

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

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

Rapidly build MCP servers for your Laravel applications.

77022.3M151](/packages/laravel-mcp)[propaganistas/laravel-disposable-email

Disposable email validator

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

Create a static site bundle from a Laravel app

674146.0k6](/packages/spatie-laravel-export)

PHPackages © 2026

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