Home > Mobile >  Laravel external api data extraction (closed)
Laravel external api data extraction (closed)

Time:10-14

Im still new in back-end development and laravel. I'm using Laravel 8.

I want to fetch an api and access only the countries data, I can't figure out how to access it individually using foreach or any other method.

here is my fetch function:

function countries()
{
    $data = Http::get('https://api.first.org/data/v1/countries');
    //return json_decode($data);
    return view('v_Country', ['data' => $data]);
}

how do I access those data in my v_Country view?

Thanks in advance

CodePudding user response:

I have created a sandbox which you can can play around with.

I created a controller called CountriesController.php which contains a similar function to yours (with just a little bit of error protection):

public function countries() {
    $countries = [];

    $response = file_get_contents('https://api.first.org/data/v1/countries');

    if($response !== false) {
        $decodedResponse = json_decode($response, true);

        if($decodedResponse !== false && isset($decodedResponse['data'])) {
            $countries = $decodedResponse['data'];
        }
    }

    return view('countries', compact('countries'));
}

Then simply in the view countries.blade.php I created the following HTML table:

<table border="1">
    <tr>
        <th>Code</th>
        <th>Country</th>
        <th>Region</th>
    </tr>
    @foreach ($countries as $code => $details)
        <tr>
            <td>{{ $code }}</td>
            <td>{{ $details['country'] }}</td>
            <td>{{ $details['region']}}</td>
        </tr>
    @endforeach
</table>
  • Related