~/docs
Resonate
Resonate
2.x 2.2.2, current
Laravel Countries
Toggle sidebar
Laravel Countries
webpatser/laravel-countries 2.2.2

Laravel Countries 2.x

Eloquent Models

Use the Country Eloquent model with query scopes, accessors, casts, and the HasCountry and CountrySelectable traits.

The Country model reads the countries table created by countries:install (or countries:migration). Install and seed the table first, see Installation.

The Country Model

The primary key is iso_3166_2, a non-incrementing string. The table name comes from config('countries.table_name').

use Webpatser\Countries\Models\Country;
 
// Find a country by its ISO 3166-1 alpha-2 code (the primary key)
$usa = Country::find('US');
echo $usa->name; // "United States"
echo $usa->full_name; // "United States of America"
echo $usa->flag; // "πŸ‡ΊπŸ‡Έ"
 
// Standard Eloquent methods
$allCountries = Country::all();
$country = Country::where('iso_3166_2', 'DE')->first();

Try it

Search Country
Try: US, DE, JP, "United States", "Germany", "Japan"

Model Attributes

Attribute Type Description
iso_3166_2 string 2-letter code (US, DE, JP), primary key
iso_3166_3 string 3-letter code (USA, DEU, JPN)
name string Common name ("United States")
full_name string, nullable Official name ("United States of America"), added in 2.2.0
capital string, nullable Capital city
region string, nullable africa, americas, asia, europe or oceania in the bundled data
currency_code string, nullable Currency code (USD, EUR, JPY)
currency_name string, nullable Currency name
currency_symbol string, nullable Currency symbol; the model returns Β€ when empty
calling_code string, nullable Calling code; the model returns it with a leading +
languages array Language codes, cast to an array
flag string, nullable Flag emoji

Query Scopes

By Region

byRegion() uses a LIKE match on region:

$europeanCountries = Country::byRegion('Europe')->get();
$asianCountries = Country::byRegion('Asia')->get();

european() is a shortcut that compares region to 'Europe' exactly. Because the bundled data stores lowercase region names, prefer byRegion('Europe') on databases with case-sensitive comparisons.

By Currency

$euroCountries = Country::byCurrency('EUR')->get();
$usdCountries = Country::byCurrency('usd')->get(); // code is upper-cased

withCurrency() keeps only countries that have a currency code.

By Language

byLanguage() matches against the stored JSON language codes:

$englishCountries = Country::byLanguage('en')->get();

Search Countries

search() looks at name, full_name, capital, iso_3166_2 and iso_3166_3 with LIKE:

$results = Country::search('united')->get();
 
$europeanUnited = Country::byRegion('Europe')
->search('united')
->get();

Try it

Filter by Region Filter by Currency Search Countries
Error: Database file at path [/home/sites/documentation.downsized.nl/releases/27/database/database.sqlite] does not exist. Ensure this is an absolute path to the database. (Connection: sqlite, Database: /home/sites/documentation.downsized.nl/releases/27/database/database.sqlite, SQL: select * from "countries" limit 20)

Showing 0 of 0 countries

No countries found matching your criteria.

Accessors and Helper Methods

$country = Country::find('US');
 
echo $country->name_with_flag; // "United States πŸ‡ΊπŸ‡Έ"
echo $country->formatted_calling_code; // "+1"
echo $country->languages_list; // "en"
 
$country->hasLanguage('en'); // true (case-insensitive, language code)
$country->hasCurrency(); // true
$country->isInRegion('Americas'); // true (case-insensitive, partial match)

Note: full_name returns the official name. Before 2.2.0 it returned the name with the flag; that accessor is now name_with_flag.

Select Options

$option = Country::find('US')->toSelectOption();
// ['value' => 'US', 'label' => 'United States πŸ‡ΊπŸ‡Έ']
 
$all = Country::getSelectOptions();
$european = Country::getSelectOptions('Europe');

Localized Names

When config('countries.localized') is true, the name attribute looks up countries.{ISO code} through Laravel's translator for the current locale and falls back to the stored name.

HasCountry Trait

HasCountry adds a belongsTo relation to Country through a country_code column on your model. Add that column to your own migration.

use Illuminate\Database\Eloquent\Model;
use Webpatser\Countries\Traits\HasCountry;
 
class User extends Model
{
use HasCountry;
 
protected $fillable = [
'name',
'email',
'country_code',
];
}
 
$user = User::create([
'name' => 'John Doe',
'email' => '[email protected]',
'country_code' => 'US',
]);
 
echo $user->country->name; // "United States"
echo $user->country_name; // "United States"
echo $user->country_flag; // "πŸ‡ΊπŸ‡Έ"
echo $user->formatted_country; // "United States πŸ‡ΊπŸ‡Έ"
 
// Query scopes
$americanUsers = User::fromCountry('US')->get();
$europeanUsers = User::fromRegion('Europe')->get();
$euroUsers = User::fromCurrency('EUR')->get();
 
// Checks
$user->isFromCountry('us'); // true
$user->isFromRegion('Europe');
$user->isFromEurope();
$user->isFromAsia();
$user->isFromAfrica();
$user->isFromOceania();

The trait also defines isFromNorthAmerica() and isFromSouthAmerica(). They match the strings "North America" and "South America" against the country region, and the bundled data uses americas, so they return false with the bundled data.

Try it

HasCountry Trait Simulation
This demo simulates how the HasCountry trait would work with a User model.

User Information

Name
Email
Country

HasCountry Trait Methods

Error: Call to undefined method Webpatser\Countries\Models\Country::findByCode()
Select a country to see trait methods in action

CountrySelectable Trait

CountrySelectable adds static option builders to any class. They read from the Countries class, so no table is needed.

use Webpatser\Countries\Traits\CountrySelectable;
 
class ProfileForm
{
use CountrySelectable;
}
 
ProfileForm::getCountrySelectOptions(); // ['AF' => 'πŸ‡¦πŸ‡« Afghanistan', ...]
ProfileForm::getCountrySelectOptions('Europe', false);
ProfileForm::getRegionSelectOptions(); // ['africa' => 'africa', ...]
ProfileForm::getCurrencySelectOptions(); // ['AFN' => 'Afghan Afghani (...)', ...], sorted by currency name
ProfileForm::getLanguageSelectOptions(); // ['af' => 'af', ...]

Casts

The Country model casts languages with CountryLanguages and flag with CountryFlag. Three cast classes are available for your own models:

Cast Behavior
Webpatser\Countries\Casts\CountryCode Upper-cases on read; upper-cases and trims on write
Webpatser\Countries\Casts\CountryFlag Returns the stored emoji; if the stored value is a single character, builds the flag from iso_3166_2
Webpatser\Countries\Casts\CountryLanguages Stores a JSON array, returns a PHP array
use Illuminate\Database\Eloquent\Model;
use Webpatser\Countries\Casts\CountryCode;
use Webpatser\Countries\Casts\CountryLanguages;
 
class Location extends Model
{
protected $casts = [
'country_code' => CountryCode::class,
'supported_languages' => CountryLanguages::class,
];
}

Relationships Without the Trait

use Illuminate\Database\Eloquent\Model;
use Webpatser\Countries\Models\Country;
 
class Order extends Model
{
public function country()
{
return $this->belongsTo(Country::class, 'country_code', 'iso_3166_2');
}
}
 
$orders = Order::with('country')->get();
 
$ordersByRegion = Order::with('country')
->get()
->groupBy('country.region');

Note: Eager load the relation (with('country')) to avoid one query per row.

Next Steps