PHPackages                             awkwardideas/laravel\_cities - 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. [Database &amp; ORM](/categories/database)
4. /
5. awkwardideas/laravel\_cities

ActiveLibrary[Database &amp; ORM](/categories/database)

awkwardideas/laravel\_cities
============================

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API &amp; a bonus vue.js component!

v1.4.0(8y ago)116MITPHP

Since Feb 28Pushed 8y ago1 watchersCompare

[ Source](https://github.com/awkwardideas/laravel_cities)[ Packagist](https://packagist.org/packages/awkwardideas/laravel_cities)[ Docs](https://github.com/awkwardideas/laravel_cities.git)[ RSS](/packages/awkwardideas-laravel-cities/feed)WikiDiscussions master Synced today

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

[![Laravel](https://camo.githubusercontent.com/5a1939c3fb1f6760124421638f59ab4ed15b6d03dbb30a6824df9af781880437/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d352e782d6f72616e67652e737667)](http://laravel.com)[![License](https://camo.githubusercontent.com/4661abfe916186acde514558e7f040833cb63ba7098401a51ce339cbb2b4cf9e/687474703a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e737667)](https://tldrlegal.com/license/mit-license)

Forked from [igaster/laravel\_cities](https://github.com/igaster/laravel_cities)
================================================================================

[](#forked-from-igasterlaravel_cities)

Introduction
============

[](#introduction)

- Deploy and use geonames.org (ex MaxCDN) database locally to query countries/cities
- Includes latitude/longitude
- Optimized [DB tree structure](https://en.wikipedia.org/wiki/Nested_set_model) for searching and traversing the tree.
- Provides an Eloquent model (geo) with multiple query-scopes to help you build your queries.
- Exposes a simple API that you can use to create AJAX calls. (Eg search while typing etc).
- A sample vue.js component that that can be inserted into your forms and provides a UI to pick a location

What you dont get:

- geoIP &amp; Postalcodes (not included in free sets)
- Map elements smaller than "3rd Administration Division" (=Cities)

Instructions
============

[](#instructions)

- Install with copmoser. Run:

`composer require awkwardideas/laravel_cities`

- Add Service Provider in app.php:

```
'providers' => [
    //...
    AwkwardIdeas\LaravelCities\GeoServiceProvider::class,
];
```

- Create a folder `geo` into app's storage folder ('\\storage\\geo'). Download &amp; unzip "hieararcy.txt" &amp; "allCountries.txt" from geonames.org ()

\[Tip\] Quick script to download on your remote server with:

```
mkdir storage/geo
cd storage/geo
wget http://download.geonames.org/export/dump/allCountries.zip && unzip allCountries.zip && rm allCountries.zip
wget http://download.geonames.org/export/dump/hierarchy.zip && unzip hierarchy.zip && rm hierarchy.zip

```

- Migrate and Seed. Run:

```
php artisan migrate
php artisan geo:seed

```

Note: If you don't want all the countries, you can download only country specific files (eg US.txt) and import each one of them with:

```
php artisan geo:seed US --append

```

Seed with custom data
=====================

[](#seed-with-custom-data)

Create a json file with custom data at `storage\geo` and run the following command to pick a file to seed:

```
php artisan geo:json

```

If an item exists in the DB (based on the 'id' value), then it will be updated else a new entry will be inserted. For example the following json file will rename `United States` to `USA` and it will add a child item (set by the parent\_id value)

```
[
  {
    "id": 6252001,
    "name": "USA"
  },
  {
    "name": "USA Child Item",
    "parent_id": 6252001,
    "lat": "39.760000",
    "long": "-98.500000"
  }
]
```

Please note that adding new items to the DB will reindex ALL items to rebuild the tree structure. Please be patient...

An example file is provided: [countryNames.json](https://github.com/awkwardideas/laravel_cities/blob/master/data/countryNames.json) which updates the official country names with a most popular simplified version.

Tip: You can get a json representation from the DB by quering the API (see below)

Geo Model:
==========

[](#geo-model)

You can use `AwkwardIdeas\LaravelCities\Geo` Model to access the database. List of available properties:

```
$geo->name;       // name of geographical point in plain ascii
$geo->country;    // 2-letter country code (ISO-3166)
$geo->id;         // Original id from geonames.org database (geonameid)
$geo->lat;        // latitude in decimal degrees (wgs84)
$geo->long;       // longitude in decimal degrees (wgs84)
$geo->level;      // Administrator level code (feature code)
// parent_id, left, right, depth: Used to build hierarcy tree
```

Visit  &gt; Info, for a more detailed description.

Usage
=====

[](#usage)

Searching:
----------

[](#searching)

```
use AwkwardIdeas\LaravelCities\Geo;

Geo::getCountries();               // Get a Collection of all countries
Geo::getCountry('US');             // Get item by Country code
Geo::findName('Nomos Kerkyras');   // Find item by (ascii) name
Geo::searchNames('york');          // Search item by all alternative names. Case insensitive
Geo::searchNames('vegas', Geo::getCountry('US'));  // ... and belongs to an item
Geo::getByIds([390903,3175395]);   // Get a Collection of items by Ids
```

Traverse tree
-------------

[](#traverse-tree)

```
$children    = $geo->getChildren();    // Get direct Children of $geo (Collection)
$parent      = $geo->getParent();      // Get single Parent of $geo (Geo)
$ancenstors  = $geo->getAncensors();   // Get Ancenstors tree of $geo from top->bottom (Collection)
$descendants = $geo->getDescendants(); // Get all Descentants of $geo alphabetic (Collection)
```

Check Hierarchy Relations:
--------------------------

[](#check-hierarchy-relations)

```
$geo1->isParentOf($geo2);       // (Bool) Check if $geo2 is direct Parent of $geo1
$geo2->isChildOf($geo1);        // (Bool) Check if $geo2 is direct Child of $geo1
$geo1->isAncenstorOf($geo2);    // (Bool) Check if $geo2 is Ancenstor of $geo1
$geo2->isDescendantOf($geo1);   // (Bool) Check if $geo2 is Descentant of $geo1
```

Query scopes (Use them to Build custom queries)
-----------------------------------------------

[](#query-scopes-use-them-to-build-custom-queries)

```
Geo::level($level);     // Filter by Administration level:
                        // Geo::LEVEL_COUNTRY, Geo::LEVEL_CAPITAL, Geo::LEVEL_1, Geo::LEVEL_2, Geo::LEVEL_3
Geo::country('US');     // (Shortcut) Items that belongs to country US
Geo::capital();         // (Shortcut) Items that are capitals
Geo::search($name);     // Items that conain $name in name OR alternames (Case InSensitive)
Geo::areDescentants($geo);   // Items that belong to $geo

$geo->ancenstors();     // Items that contain $geo
$geo->descendants();    // Items that belong to $geo
$geo->children();       // Items that are direct children of $geo

//--Scope usage Examples:

// Get the States of USA in aplhabetic order
Geo::getCountry('US')
	->children()
	->orderBy('name')
	->get();

// Get the 3 biggest cities of Greece
Geo::getCountry('GR')
	->level(Geo::LEVEL_3)
	->orderBy('population','DESC')
	->limit(3)
	->get();
```

If you need more functionality you can extend `AwkwardIdeas\LaravelCities\Geo` model and add your methods.

HTTP API
========

[](#http-api)

This package defines some API routes that can be used to query the DB through simple HTTP requests. To use them insert in your routes file:

```
\AwkwardIdeas\LaravelCities\Geo::ApiRoutes();
```

For example if you insert them in your `routes\api.php` (recommended) then the following URLs will be registered:

URL Endpoind (GET)DescriptionReturns (JSON)api/geo/search/{name}/{parent-id?}Search items containing 'name', (and belong to parent-id)Collectionapi/geo/item/{id}Get item by idGeoapi/geo/items/{ids}Get multiple items by ids (comma seperated list)Collectionapi/geo/children/{id}Get children of itemCollectionapi/geo/parent/{id}Get parent of itemGeoapi/geo/country/{code}get country by two-letter codeGeoapi/geo/countrieslist of countriesCollectionThe response is always a JSON representation of either a Geo class or a Collection.

To reduce bandwith, all Geo model attributes will be returned except from `alternames`, `left`, `right` and `depth`. You can change this behavior by passing an optional parameter on any request:

URL Params (aplly to all routes)DescriptionExamplefields=field1,field2Returns only the specified attributesapi/geo/countries?fields=id,namefields=allReturns all attributesapi/geo/countries?fields=allVue Component
=============

[](#vue-component)

A [Vue component](https://github.com/awkwardideas/laravel_cities/blob/master/vue/geo-slect.vue) is shipped with this package that plugs into the provided API and provides an interactive way to pick a location through a series of steps. Sorry, no live demo yet, just some screenshots:

Step 1: Select your location. Drop down lists loads asynchronous:

[![Select Location](/docs/1.jpg?raw=true)](/docs/1.jpg?raw=true)

Step 2: Reached to a destination. Path is displayed and button to edit selection:

[![Finished Selection](/docs/2.jpg?raw=true)](/docs/2.jpg?raw=true)

Step 3: On form submition several fields are beeing submited:

[![Form Submited](/docs/3.jpg?raw=true)](/docs/3.jpg?raw=true)

### Usage Guide

[](#usage-guide)

Assuming that you are using Webpack to compile your assets, and you have included `vue-app.js`:

### Add in your application

[](#add-in-your-application)

In your main vue-app.js file add the component declaration:

`Vue.component('geo-select', require('RELATIVE_PATH_TO/vendor/awkwardideas/laravel_cities/src/vue/geo-select.vue'));`

Alternative you may publish the component with

`artisan vendor:publish --provider="AwkwardIdeas\LaravelCities\GeoServiceProvider"`

Component will be exported at `/resources/LaravelCities/geo-select.vue` so that you can make modifications...

If you choose to do the exported component, make sure you register it in the vue-app.js file with

`Vue.component('geo-select', require('RELATIVE_PATH_TO/resources/LaravelCities/geo-select.vue'));`

### Compile compoment

[](#compile-compoment)

`npm run dev` (or `npm run production`)

### Use in blade files

[](#use-in-blade-files)

Example:

```

```

The following inputs will be submited:

- geo-id
- geo-name
- geo-long
- geo-lat
- geo-country
- geo-country-code

### Full syntax:

[](#full-syntax)

```

```

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity69

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 ~47 days

Recently: every ~100 days

Total

10

Last Release

2929d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/771bc8e6daa6dea7b49ed5a97d38e0aa83c2abd0d32a97074d2eebac40383c49?d=identicon)[awkwardideas](/maintainers/awkwardideas)

---

Top Contributors

[![igaster](https://avatars.githubusercontent.com/u/4586319?v=4)](https://github.com/igaster "igaster (77 commits)")

---

Tags

laravelgeolocationcountriescitiesGeoNames.org

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[nnjeim/world

Laravel countries, states, cities, currencies, languages and IP geolocation

970361.2k3](/packages/nnjeim-world)[igaster/laravel_cities

Seed all countries/cities from geonames.org database. Searchable DB tree, ready to use API &amp; a bonus vue.js component!

17988.7k1](/packages/igaster-laravel-cities)[lwwcas/laravel-countries

A comprehensive package for managing country data in Laravel applications, including multilingual support, geographic coordinates, and detailed metadata for seamless integration with Laravel.

12464.0k](/packages/lwwcas-laravel-countries)[altwaireb/laravel-world

Laravel World, Countries States Cities DB Migration &amp; Seeder

989.4k](/packages/altwaireb-laravel-world)[tpetry/laravel-mysql-explain

Get Visual MySQL EXPLAIN for Laravel.

264154.2k](/packages/tpetry-laravel-mysql-explain)[io238/laravel-iso-countries

Ready-to-use Laravel models and relations for country (ISO 3166), language (ISO 639-1), and currency (ISO 4217) information with multi-language support.

5462.3k](/packages/io238-laravel-iso-countries)

PHPackages © 2026

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