Installation:
composer require lwwcas/laravel-countries
php artisan vendor:publish --provider="Lwwcas\Countries\CountriesServiceProvider" --tag="countries-config"
config/countries.php and resources/lang/.First Use Case: Fetch all countries with their default names:
use Lwwcas\Countries\Facades\Countries;
$countries = Countries::all(); // Collection of Country models
$firstCountry = Countries::first(); // First country in the list
Basic Querying:
// Get a country by ISO code
$country = Countries::find('US');
// Get countries by continent
$europeanCountries = Countries::where('continent', 'Europe')->get();
Multilingual Support:
// Set language (e.g., for Spanish)
app()->setLocale('es');
$countryName = Countries::find('ES')->name; // Returns "España"
Country Data Retrieval:
with() to load related data (e.g., currencies, languages):
$country = Countries::with('currencies', 'languages')->find('CA');
Countries::chunk(100, function ($countries) {
foreach ($countries as $country) {
// Process each country
}
});
Filtering and Searching:
$results = Countries::where('name', 'like', '%France%')
->orWhere('iso2', 'FR')
->get();
calling_code):
$countries = Countries::where('calling_code', '1')->get(); // North America
Integration with Eloquent Models:
// In a User model
public function country()
{
return $this->morphTo();
}
// Store a country on a user
$user->country()->associate(Countries::find('JP'));
$user->save();
Localization:
Countries::setLocale('fr'); // Override app locale for this request
$countryName = Countries::find('DE')->name; // "Allemagne"
config/countries.php:
'locales' => [
'default' => 'en',
'fallback' => ['en', 'es'],
],
Geospatial Queries:
$nearbyCountries = Countries::whereBetween('latitude', [40, 50])
->whereBetween('longitude', [-10, 10])
->get();
Caching:
$countries = Cache::remember('all_countries', now()->addHours(1), function () {
return Countries::all();
});
API Integration:
// Example: Sync with an external API
$externalData = Http::get('https://restcountries.com/v3.1/all');
Countries::syncFromExternal($externalData);
Custom Collections:
use Lwwcas\Countries\Country;
$customCollection = collect(Countries::all())
->map(fn (Country $country) => [
'id' => $country->iso3,
'label' => $country->name,
]);
Validation Rules:
use Lwwcas\Countries\Rules\ValidCountry;
public function rules()
{
return [
'country_code' => ['required', new ValidCountry],
];
}
Event Listeners:
CountryRetrieved):
// In EventServiceProvider
protected $listen = [
\Lwwcas\Countries\Events\CountryRetrieved::class => [
\App\Listeners\LogCountryAccess::class,
],
];
Locale Mismatches:
php artisan vendor:publish --tag="countries-lang"
Verify config/countries.php has the correct locales array.Case Sensitivity in ISO Codes:
Countries::find('us') returns null (ISO codes are uppercase).$country = Countries::find(strtoupper($userInput));
Missing Data:
region).fillMissing() to provide defaults:
$country = Countries::find('BV')->fillMissing([
'region' => 'Antarctica',
]);
Performance with Large Datasets:
$countries = Countries::paginate(50);
Timezone Confusion:
$country = Countries::find('AU')->validateCoordinates();
Inspect Raw Data:
dd(Countries::getRawData());
Check Published Config:
config/countries.php:
'enabled' => env('COUNTRIES_ENABLED', true),
'cache_driver' => env('COUNTRIES_CACHE_DRIVER', 'array'),
Enable Query Logging:
\DB::enableQueryLog();
$countries = Countries::all();
dd(\DB::getQueryLog());
Validate ISO Codes:
isValidIsoCode() helper:
if (!\Lwwcas\Countries\Helpers::isValidIsoCode('XX')) {
// Handle invalid code
}
Custom Fields:
// In Country model
public function getFullNameAttribute()
{
return "{$this->name} ({$this->iso3})";
}
Override Data Sources:
$this->app->bind(\Lwwcas\Countries\Contracts\CountryDataSource::class, function () {
return new \App\Services\CustomCountryDataSource;
});
Add New Languages:
php artisan vendor:publish --tag="countries-lang" --force
Add translations to resources/lang/{locale}/countries.php.Hook into Data Loading:
Country model to modify data on retrieval:
protected static function boot()
{
parent::boot();
static::retrieved(function ($country) {
$country->setAttribute('custom_field', 'value');
});
}
Create Custom Query Scopes:
Country model:
public function scopeByRegion($query, $region)
{
return $query->where('region', $region);
}
Usage:
$countries = Countries::byRegion('Europe')->get();
Cache Driver:
config/countries.php matches your .env:
'cache_driver' => env('COUNTRIES_CACHE_DRIVER', 'file'),
array, file, database, redis, etc.Data Syncing:
How can I help you explore Laravel packages today?