Collection Macros

Extend Laravel Collections with powerful country-specific methods.

Available Collection Macros

Laravel Countries adds several macros to Laravel Collections, making it easy to work with country data in a fluent, expressive way:

Macro
Purpose
Returns
byRegion() Filter countries by region Filtered Collection
byCurrency() Filter countries by currency Filtered Collection
searchCountries() Search countries by name or capital Filtered Collection
countryNames() Extract country names only Collection of names
countryFlags() Extract country flags only Collection of flags
countryCodes() Extract country codes only Collection of codes

Basic Usage

First, create a collection from your countries data:

use Webpatser\Countries\Countries;
 
// Create a collection from all countries
$countries = collect((new Countries())->getList());
 
// Or from a subset
$someCountries = collect([
'US' => ['name' => 'United States', 'region' => 'Americas', 'currency_code' => 'USD'],
'DE' => ['name' => 'Germany', 'region' => 'Europe', 'currency_code' => 'EUR'],
'JP' => ['name' => 'Japan', 'region' => 'Asia', 'currency_code' => 'JPY'],
]);
Try Collection Macros
Experiment with different macros and see the results:

Filtering Macros

Filter by Region

// Get all European countries
$europeanCountries = $countries->byRegion('Europe');
 
// Get all Asian countries
$asianCountries = $countries->byRegion('Asia');
 
// Chain with other collection methods
$europeanNames = $countries
->byRegion('Europe')
->countryNames()
->sort();

Filter by Currency

// Get all countries using Euro
$euroCountries = $countries->byCurrency('EUR');
 
// Get all countries using US Dollar
$usdCountries = $countries->byCurrency('USD');
 
// Get country names using specific currency
$euroCountryNames = $countries
->byCurrency('EUR')
->countryNames();

Search Countries

// Search by country name
$unitedCountries = $countries->searchCountries('united');
 
// Search by capital city
$londonResults = $countries->searchCountries('london');
 
// Case-insensitive search
$franceResults = $countries->searchCountries('FRANCE');

Data Extraction Macros

Extract Names

// Get all country names
$names = $countries->countryNames();
// ['United States', 'Germany', 'Japan', ...]
 
// Get names from filtered countries
$europeanNames = $countries
->byRegion('Europe')
->countryNames()
->sort();
// ['Austria', 'Belgium', 'France', 'Germany', ...]

Extract Flags

// Get all country flags
$flags = $countries->countryFlags();
// ['🇺🇸', '🇩🇪', '🇯🇵', ...]
 
// Get flags from specific region
$asianFlags = $countries
->byRegion('Asia')
->countryFlags();
// ['🇯🇵', '🇨🇳', '🇮🇳', ...]

Extract Country Codes

// Get all country codes
$codes = $countries->countryCodes();
// ['US', 'DE', 'JP', ...]
 
// Get codes from filtered countries
$euroCodes = $countries
->byCurrency('EUR')
->countryCodes();
// ['DE', 'FR', 'IT', 'ES', ...]

String Macros

Laravel Countries also extends the Str class with country utilities:

use Illuminate\Support\Str;
 
// Convert country codes to flags
$flag = Str::toCountryFlag('US'); // "🇺🇸"
$flag = Str::toCountryFlag('DE'); // "🇩🇪"
 
// Convert flags back to codes
$code = Str::fromCountryFlag('🇺🇸'); // "US"
$code = Str::fromCountryFlag('🇩🇪'); // "DE"
 
// Get country names
$name = Str::countryName('FR'); // "French Republic"
$name = Str::countryName('JP'); // "Japan"

Advanced Chaining

Combine multiple macros for powerful data processing:

// Get European country names sorted alphabetically
$result = $countries
->byRegion('Europe')
->countryNames()
->sort()
->values();
 
// Get currencies used in Asia
$asianCurrencies = $countries
->byRegion('Asia')
->pluck('currency_code')
->unique()
->sort()
->values();
 
// Find countries with 'United' in the name, get their flags
$unitedFlags = $countries
->searchCountries('United')
->countryFlags();
 
// Complex filtering: European countries using Euro, get formatted list
$euroEuropean = $countries
->byRegion('Europe')
->byCurrency('EUR')
->map(fn($country, $code) => Str::toCountryFlag($code) . ' ' . $country['name'])
->sort()
->values();

Real-world Use Cases

Building Select Options

// Create select options for a form
$europeanOptions = $countries
->byRegion('Europe')
->map(fn($country, $code) => [
'value' => $code,
'label' => $country['flag'] . ' ' . $country['name']
])
->sortBy('label')
->values();
 
// For HTML select
$selectOptions = $countries
->byRegion('Europe')
->countryNames()
->sort()
->map(fn($name, $code) => "<option value='{$code}'>{$name}</option>")
->implode('');

Analytics and Reporting

// Group countries by currency for reporting
$currencyGroups = $countries
->groupBy('currency_code')
->map(fn($group) => $group->countryNames()->sort())
->sortKeys();
 
// Get statistics by region
$regionStats = $countries
->groupBy('region')
->map(fn($group) => [
'count' => $group->count(),
'currencies' => $group->pluck('currency_code')->unique()->count(),
'countries' => $group->countryNames()->sort()->take(5)->values()
]);

API Response Formatting

// Format API response with country data
$apiResponse = $countries
->byRegion($request->region)
->when($request->currency, fn($c) => $c->byCurrency($request->currency))
->when($request->search, fn($c) => $c->searchCountries($request->search))
->take(20)
->map(fn($country, $code) => [
'code' => $code,
'name' => $country['name'],
'flag' => $country['flag'],
'currency' => [
'code' => $country['currency_code'],
'symbol' => $country['currency_symbol']
]
])
->values();

Performance Considerations

Macro Performance
Collection macros are memory-efficient and fast:
  • • Macros work on existing collections without loading extra data
  • • Filtering is done in PHP, not database queries
  • • Chain operations for optimal performance
// Good: Chain operations to minimize iterations
$result = $countries
->byRegion('Europe')
->byCurrency('EUR')
->countryNames()
->sort();
 
// Less efficient: Multiple separate operations
$european = $countries->byRegion('Europe');
$euro = $european->byCurrency('EUR');
$names = $euro->countryNames();
$sorted = $names->sort();