shahadatjuton/geo-code

A comprehensive Laravel package providing countries, states, cities, and postal codes data with multi-language support

Maintainers

Package info

github.com/shahadatjuton/geo-code

pkg:composer/shahadatjuton/geo-code

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-03-08 09:20 UTC

This package is auto-updated.

Last update: 2026-03-08 18:25:12 UTC


README

Latest Version on Packagist Total Downloads License PHP Version

A comprehensive Laravel package providing complete geographical data for all 250+ countries, 5,000+ states/provinces, and 150,000+ cities with multi-language support. Built for production use with automatic data downloading, caching, and API endpoints.

πŸ“¦ Package: shahadatjuton/geo-code πŸ”— Repository: github.com/shahadatjuton/geo-code

use Shahadatjuton\GeoCode\Facades\GeoCode;

// Get all countries with one line
$countries = GeoCode::getAllCountries();

// Access any country's complete data
$usa = GeoCode::getCountry('US'); // States, cities, everything
$states = GeoCode::getStatesByCountry('US'); // 50 US states
$cities = GeoCode::getCitiesByState($californiaId);

Features

  • 🌍 Complete worldwide coverage - All 250+ countries including non-UN members and territories
  • πŸš€ Automatic data download - One command downloads everything from source
  • 🎯 Flexible data import - Download all data OR specific countries, states, cities, postal codes separately
  • πŸ”§ Country-specific downloads - Download only data for specific countries to save space and time
  • ⚑ High performance - Built-in caching, batch processing, optimized queries
  • 🌐 Multi-language support - Country names in 11 languages (EN, ES, FR, DE, IT, PT, RU, ZH, JA, AR, HI)
  • πŸ”Œ API ready - RESTful endpoints included
  • πŸ“¦ Laravel 9-12 support - Full compatibility with Laravel 9, 10, 11, and 12
  • 🎯 Framework agnostic - Works with Laravel, CodeIgniter, WordPress, or any PHP framework
  • πŸ› οΈ Easy to use - Facade, helpers, Eloquent models, and API endpoints
  • βœ… Production ready - Tests, error handling, data verification included

Installation

Install via Composer:

composer require shahadatjuton/geo-code

Publish and run migrations:

php artisan vendor:publish --tag=geocode-config
php artisan migrate

Option 1: Download All Global Data

Download and seed all geographical data (countries, states, cities):

php artisan geocode:download --all
php artisan geocode:seed --all

Option 2: Download Specific Data Types

Download and seed only what you need:

# Download and seed only countries
php artisan geocode:download --countries
php artisan geocode:seed --countries

# Download and seed countries and states
php artisan geocode:download --countries --states
php artisan geocode:seed --countries --states

# Download and seed with postal codes
php artisan geocode:download --all --postal-codes
php artisan geocode:seed --all

Option 3: Download Data for Specific Countries

Download and seed data only for specific countries:

# United States with all data
php artisan geocode:download --country=US --with-states --with-cities --with-postal-codes
php artisan geocode:seed --country=US

# United Kingdom with states and cities
php artisan geocode:download --country=GB --with-states --with-cities
php artisan geocode:seed --country=GB

# India with states only
php artisan geocode:download --country=IN --with-states
php artisan geocode:seed --country=IN

# Multiple countries (run commands separately for each)
php artisan geocode:download --country=US --with-states --with-cities
php artisan geocode:seed --country=US
php artisan geocode:download --country=CA --with-states --with-cities
php artisan geocode:seed --country=CA

That's it! You now have geographical data tailored to your needs.

Flexible Download Options

This package gives you complete control over what data to download and seed:

By Data Type

  • Download countries only for lightweight apps
  • Download countries + states for regional applications
  • Download countries + states + cities for full location support
  • Download postal codes separately when needed

By Geographic Region

  • Download data for specific countries (e.g., only US, UK, India)
  • Download states, cities, postal codes for specific countries
  • Mix and match based on your application needs

Benefits

  • Faster setup - Download only what you need
  • Smaller database - Reduce storage requirements by 90%+ for single-country apps
  • Better performance - Smaller tables mean faster queries
  • Cost savings - Less storage and bandwidth usage

Use Cases

E-commerce (US-only):

php artisan geocode:download --country=US --with-states --with-cities --with-postal-codes
php artisan geocode:seed --country=US
# Result: ~50 states, ~40,000 cities instead of 5,000 states, 150,000 cities globally

SaaS (Multi-region):

php artisan geocode:download --country=US --with-states --with-cities
php artisan geocode:download --country=GB --with-states --with-cities
php artisan geocode:download --country=IN --with-states --with-cities
php artisan geocode:seed --country=US
php artisan geocode:seed --country=GB
php artisan geocode:seed --country=IN
# Result: Only data for your target markets

Simple country selector:

php artisan geocode:download --countries
php artisan geocode:seed --countries
# Result: Just 250 countries, no states/cities needed

Quick Start

Get Countries

use Shahadatjuton\GeoCode\Facades\GeoCode;

// All countries
$countries = GeoCode::getAllCountries();

// Specific country
$usa = GeoCode::getCountry('US');
$uk = GeoCode::getCountry('GB');

// By region
$european = Country::where('region', 'Europe')->get();

Get States & Cities

// Get states by country
$usStates = GeoCode::getStatesByCountry('US'); // 50 states

// Get cities by state
$cities = GeoCode::getCitiesByState($stateId);

// Get cities by country
$allUSCities = GeoCode::getCitiesByCountry('US');

Search

// Search countries
$results = GeoCode::searchCountries('united');
// Returns: United States, United Kingdom, UAE

// Search cities
$results = GeoCode::searchCities('los angeles', 'US');

Multi-language

// Get country names in different languages
$name = GeoCode::getCountry('CN', 'en'); // China
$name = GeoCode::getCountry('CN', 'es'); // China
$name = GeoCode::getCountry('CN', 'zh'); // δΈ­ε›½
$name = GeoCode::getCountry('CN', 'ja'); // δΈ­ε›½
$name = GeoCode::getCountry('CN', 'ar'); // Ψ§Ω„Ψ΅ΩŠΩ†

Helper Functions

// Get countries for dropdown
$countries = geocode_countries(); // ['US' => 'United States', ...]

// Get country name
$name = geocode_country('US'); // United States
$name = geocode_country('US', 'es'); // Estados Unidos

// Get states for dropdown
$states = geocode_states('US'); // [1 => 'California', ...]

// Format address
$address = geocode_format_address($cityId, $stateId, 'US');
// Returns: "Los Angeles, California, United States"

// Calculate distance
$km = geocode_distance($lat1, $lon1, $lat2, $lon2);

Usage Examples

Country-State-City Dropdown

<select name="country" id="country">
    <option value="">Select Country</option>
    @foreach(geocode_countries() as $code => $name)
        <option value="{{ $code }}">{{ $name }}</option>
    @endforeach
</select>

<select name="state" id="state">
    <option value="">Select State</option>
</select>

<select name="city" id="city">
    <option value="">Select City</option>
</select>

<script>
document.getElementById('country').addEventListener('change', function() {
    fetch(`/api/geocode/states/${this.value}`)
        .then(r => r.json())
        .then(states => {
            const select = document.getElementById('state');
            select.innerHTML = '<option value="">Select State</option>';
            states.forEach(s => {
                select.innerHTML += `<option value="${s.id}">${s.name}</option>`;
            });
        });
});

document.getElementById('state').addEventListener('change', function() {
    fetch(`/api/geocode/cities/${this.value}`)
        .then(r => r.json())
        .then(cities => {
            const select = document.getElementById('city');
            select.innerHTML = '<option value="">Select City</option>';
            cities.forEach(c => {
                select.innerHTML += `<option value="${c.id}">${c.name}</option>`;
            });
        });
});
</script>

Store Locator

use Shahadatjuton\GeoCode\Helpers\GeoCodeHelper;

$userLat = 34.0522;  // Los Angeles
$userLon = -118.2437;

// Find nearest cities
$nearest = GeoCodeHelper::findNearestCities($userLat, $userLon, 10);

foreach ($nearest as $item) {
    echo "{$item['city']->name} - {$item['distance']} km away\n";
}

Using with Eloquent

use Shahadatjuton\GeoCode\Models\Country;

// Get country with all states and cities
$usa = Country::with('states.cities')
    ->where('iso2', 'US')
    ->first();

// Get countries by region
$africanCountries = Country::where('region', 'Africa')->get(); // 54 countries

// Search countries
$countries = Country::where('name', 'LIKE', '%island%')->get();

API Endpoints

The package provides RESTful API endpoints:

GET /api/geocode/countries              - Get all countries
GET /api/geocode/states/{countryCode}   - Get states by country
GET /api/geocode/cities/{stateId}       - Get cities by state
GET /api/geocode/postal-codes/{cityId}  - Get postal codes by city
GET /api/geocode/search/countries/{q}   - Search countries
GET /api/geocode/search/cities/{q}      - Search cities

Example:

// Fetch all countries
fetch('/api/geocode/countries')
    .then(r => r.json())
    .then(countries => console.log(countries));

// Get US states
fetch('/api/geocode/states/US')
    .then(r => r.json())
    .then(states => console.log(states));

Data Coverage

Countries (250+)

  • All 193 UN member states
  • Non-UN members (Taiwan, Vatican City, Kosovo, Palestine, etc.)
  • Special territories (Hong Kong, Puerto Rico, Guam, Gibraltar, Greenland, etc.)

By Region:

  • Africa: 54 countries
  • Asia: 48 countries
  • Europe: 50 countries
  • Americas: 35 countries
  • Oceania: 14 countries

States/Provinces (5,000+)

  • United States: 50 states + DC + territories
  • Canada: 10 provinces + 3 territories
  • India: 28 states + 8 union territories
  • China: 34 provincial-level divisions
  • Russia: 85 federal subjects
  • Brazil: 26 states + federal district
  • Australia: 6 states + 10 territories
  • All other countries with administrative divisions

Cities (150,000+)

  • All capital cities
  • Major metropolitan areas
  • Secondary cities and towns
  • Coordinates (latitude/longitude) for all

Postal Codes (Optional)

Available for many countries including USA, Canada, UK, Germany, France, and more.

Commands

Download Data

# Download all data
php artisan geocode:download --all

# Download specific types
php artisan geocode:download --countries
php artisan geocode:download --states
php artisan geocode:download --cities
php artisan geocode:download --postal-codes

# Download data for specific country
php artisan geocode:download --country=US
php artisan geocode:download --country=GB --with-states --with-cities
php artisan geocode:download --country=IN --with-states --with-cities --with-postal-codes

# Country-specific options
# --country=CODE        : Specify country by ISO2 code (e.g., US, GB, IN, DE)
# --with-states         : Include states for the country
# --with-cities         : Include cities for the country
# --with-postal-codes   : Include postal codes for the country

Seed Database

# Seed all data
php artisan geocode:seed --all

# Seed specific types
php artisan geocode:seed --countries
php artisan geocode:seed --states
php artisan geocode:seed --cities
php artisan geocode:seed --postal-codes

# Seed data for specific country
php artisan geocode:seed --country=US
php artisan geocode:seed --country=GB
php artisan geocode:seed --country=IN

# Options
php artisan geocode:seed --all --truncate      # Clear existing data first
php artisan geocode:seed --all --chunk=2000    # Adjust batch size

Complete Workflows

# Workflow 1: Download and seed all global data
php artisan geocode:download --all
php artisan geocode:seed --all

# Workflow 2: Download and seed only countries
php artisan geocode:download --countries
php artisan geocode:seed --countries

# Workflow 3: Download and seed specific country with all data
php artisan geocode:download --country=US --with-states --with-cities --with-postal-codes
php artisan geocode:seed --country=US

# Workflow 4: Download and seed only states and cities for a country
php artisan geocode:download --country=GB --with-states --with-cities
php artisan geocode:seed --country=GB

# Workflow 5: Download multiple specific data types
php artisan geocode:download --countries --states
php artisan geocode:seed --countries --states

Verify Data

# Quick verification
php artisan geocode:verify

# Detailed statistics
php artisan geocode:verify --detailed

Clear Cache

php artisan geocode:update --clear-cache

Configuration

Publish the configuration file:

php artisan vendor:publish --tag=geocode-config

Edit config/geocode.php:

return [
    // Default locale
    'locale' => 'en',

    // Database connection
    'connection' => null,

    // Table names
    'tables' => [
        'countries' => 'countries',
        'states' => 'states',
        'cities' => 'cities',
        'postal_codes' => 'postal_codes',
    ],

    // Caching
    'cache' => [
        'enabled' => true,
        'duration' => 1440, // 24 hours
    ],

    // Supported locales
    'supported_locales' => [
        'en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'zh', 'ja', 'ar', 'hi'
    ],
];

Using Without Laravel

For non-Laravel projects (CodeIgniter, WordPress, plain PHP):

require_once 'vendor/autoload.php';

use Illuminate\Database\Capsule\Manager as Capsule;
use Shahadatjuton\GeoCode\Models\Country;

// Setup database connection
$capsule = new Capsule;
$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'your_database',
    'username'  => 'your_username',
    'password'  => 'your_password',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
]);

$capsule->setAsGlobal();
$capsule->bootEloquent();

// Now use the models
$countries = Country::all();
$usa = Country::where('iso2', 'US')->first();

Data Source

Data is sourced from the Countries States Cities Database, a comprehensive, regularly updated, open-source geographical database.

Coverage:

  • 250 countries
  • 5,074 states/provinces
  • 150,682 cities
  • Regular monthly updates

Testing

composer test

Or run PHPUnit directly:

vendor/bin/phpunit

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

Made with ❀️ by Shahadat Juton