Skip to content
Advertisement

How to filter json api response by id laravel

I am making a call to an endpoint to get back data which returns a lot of it. I need to partition the ones I need grouped into my own category. Basically when I make the call I get this sample response.

{
    "status": "success",
    "message": "bill categories retrieval successful",
    "data": [{
        "id": 1,
        "biller_code": "BIL099",
        "name": "MTN NIgeria",
        "default_commission": 0.03,
        "date_added": "2018-07-03T00:00:00Z",
        "country": "NG",
        "is_airtime": true,
        "biller_name": "AIRTIME",
        "item_code": "AT099",
        "short_name": "MTN",
        "fee": 0,
        "commission_on_fee": false,
        "label_name": "Mobile Number",
        "amount": 0
    }, {
        "id": 2,
        "biller_code": "BIL099",
        "name": "GLO Nigeria",
        "default_commission": 0.03,
        "date_added": "2018-07-03T00:00:00Z",
        "country": "NG",
        "is_airtime": true,
        "biller_name": "AIRTIME",
        "item_code": "AT099",
        "short_name": "GLO",
        "fee": 0,
        "commission_on_fee": false,
        "label_name": "Mobile Number",
        "amount": 0
    }, 
... //on and on
}

In my code I have this to filter it but it returns empty…

public function billPower()
{
    $response = Http::withToken('FLWSECK_******-X')->get('https://baseUrl/v3/bill-categories', [

    ]);
    $collection = collect($response->json());
    $filtered = $collection->whereIn('id', [1, 2, 3, 4]);
    return $filtered->all();
}

How can I do this in laravel?

Advertisement

Answer

you need to do:

$collection = collect($response->json()['data']);

then your filter should work

$filtered = $collection->whereIn('id', [1, 2, 3, 4]);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement