Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

webfuelcode's avatar

How to prepare loop in the controller from the API call

I am using API to collect the data. These are price tables and will appear in line graph. So trying to get the foreach loop in the controller.

function coin($id)
    {
        $host = config('coinranking_api_host');
        $key = config('coinranking_api_key');
        $price = Http::withHeaders([
            'x-rapidapi-host' => $host,
            'x-rapidapi-key' => $key
        ])->get('https://api.site.com/v2/coin/'. $id . '/history?timePeriod=3h');
=============foreach================
        return view('coin',  'price'=>$price['data']]);
    }

Data from API is here:

{
"status": "success",
    "data": {
        "change": "16.71",
        "history": [
            {
                "price": "43801.67690112498",
                "timestamp": 1644588000
            },
            {
                "price": "43605.27915203707",
                "timestamp": 1644584400
            },
            {
                "price": "43379.636793891084",
                "timestamp": 1644580800
            },
            {
                "price": "43498.921013595995",
                "timestamp": 1644577200
            }
]
}
}
0 likes
1 reply
NemoPS's avatar

I think you can use $price->json()['data']['history']

Please or to participate in this conversation.