antonioribeiro / countries

Laravel countries and currencies
BSD 3-Clause "New" or "Revised" License
1.83k stars 281 forks source link

List of country states #23

Open goper-leo opened 7 years ago

goper-leo commented 7 years ago

I will get all of country state using this code $countries = Countries::all(); I loop all of the countries and I've used contains to determine that $country have no states.

if ($country->contains('states')) {
            echo(' have state');
 } else {
            echo('  no state');
}

So here I found out Antigua and Barbuda have no state it that if condition cathes it but on the "Republic of Kosovo" , "Republic of Serbia", "Republic of South Sudan" it throws error. because it passes the if else condition even that countries have no state. I dump the results but it is the same to "Antigua and Barbuda" states => null. Here is my code: AG XK RS SS - these countries have no states that throwing error except AG

$states = Countries::where('cca2', 'SS')->first();

        echo '<br>';
        echo $states->cca2 . ' ' . $states->name->official;
        if ($states->contains('states')) {
            echo(' have state');
        } else {
            echo(' no state');
        }
        dd($states);
robfrancken commented 6 years ago

I was trying to do something similar, but I found that $country->contains('states') doesn't work, because the hydrated array key also contains a value called states, so in my case $country->contains('states') always returns true.

To get around the issue, I accessed the $country['states'] like a normal array, and that seems more reliable.

Route::get('/test', function () {
    $countries = PragmaRX\Countries\Facade::all();
    foreach ($countries as $country) {
        if(empty($country['states'])) {
            // All the countries with no
            printf('<p>No states: %s</p>', $country->name->common);
        } else {
            // All the countries with states
            printf('<p>Has states: %s</p>', $country->name->common);
            foreach ($country['states'] as $state) {
                var_dump($state);
            }
        }
    }
});