skip to Main Content

I got this data from an external API call.

$countries = @file_get_contents('https://external../api/countries'); 
$countriesArray = json_decode($countries, true);
print_r($countriesArray); 
//dd($countriesArray); 
Array
(
    [success] => 1
    [message] => countries
    [data] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Afghanistan
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => Ă…land Islands
                )

            [2] => Array
                (
                    [id] => 3
                    [name] => Albania
                )

            [3] => Array
                (
                    [id] => 4
                    [name] => Algeria
                ) 
                ....

When try the dd
dd($countriesArray)result is ok

enter image description here

When try to display the result in loop, I got this error

Attempt to read property "id" on bool

<select class="form-control" name="country" id="country">
    @foreach($countriesArray as $key => $country)
        <option
            value="{{$country->id}}" {{ old('country_id', $user->country_id) == $country->id ? 'selected' : '' }}>
            @lang($country->name)
        </option>
    @endforeach
</select>

What is the problem?

2

Answers


  1. seems like you are treating the elements of the $countriesArray as objects, but they are actually arrays.
    try access the elements using square brackets

    <select class="form-control" name="country" id="country">
        @foreach($countriesArray as $key => $country)
            <option
                value="{{ $country['id'] }}" {{ old('country_id', $user->country_id) == $country['id'] ? 'selected' : '' }}>
                @lang($country['name'])
            </option>
        @endforeach
    </select>
    
    Login or Signup to reply.
  2. As per your result, data key $countriesArray contains data in array format.

    @if(!empty($countriesArray['data']))
        @foreach($countriesArray['data'] as $key => $country)
                <option
                    value="{{$country['id']}}" {{ old('country_id', $user->country_id) == $country['id'] ? 'selected' : '' }}>
                    @lang($country['name'])
                </option>
            @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search