brnysn/laravel-world

The simplest way to add country, state and city to Laravel application.

2.0.0 2023-09-19 13:44 UTC

README

Latest Version on Packagist GitHub Code Style Action Status Total Downloads

The simplest way to add country, state and city to Laravel application.

Data is taken from dr5hn/countries-states-cities-database. Thanks to dr5hn for the great work.

Data is last updated on 2022-10-26.

Installation

Install the package via composer:

composer require brnysn/laravel-world

Publish the config file with:

php artisan vendor:publish --tag="world-config"

Define whether to use uuid or id in the config file: Migrations will be created according to this setting.

return [
    'use_uuid' => false,
];

Publish and run the migrations with:

php artisan vendor:publish --tag="world-migrations"
php artisan migrate

After the migration has been published you can add the countries, states and cities to your database by running:

php artisan db:seed --class="Brnysn\\World\\Database\\Seeders\\WorldSeeder"

Seeding the database will take a while.

Add HasWorldAddress trait to your models to add the country, state and city relationship:

use Brnysn\World\Traits\HasWorldAddress;

class {class_name} extends Model
{
    use HasWorldAddress;
}

Usage

// Get Data
use Brnysn\World\Models\Country;
use Brnysn\World\Models\State;
use Brnysn\World\Models\City;

$country = Country::find(1);
$state = State::find(1);
$city = City::find(1);

// Get Relationship
$country->states;
$state->cities;
$city->state;
$city->country;

// Query
$country->states()->where('name', 'like', '%state%')->get();
$state->cities()->where('name', 'like', '%city%')->get();

// Set Address of a model with HasWorldAddress trait
$model->changeCountry($country);
$model->changeState($state);
$model->changeCity($city);
$model->changeAddress($country, $state, $city);

// Get details of address of a model with HasWorldAddress trait
$model->country->name;
$model->state->name;

Changelog

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

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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