Klapsius
Klapsius

Reputation: 3359

Laravel API response conversion into collection

I'm playing with API responses for a while and I can't convert them into Laravel collection format.

My response after $users = json_decode($users, true); is something like that:

array:2 [▼
  "@odata.context" => "https://URL/Something.svc/$metadata#Something"
  "value" => array:190 [▼
    0 => array:18 [▶]
    1 => array:18 [▶]
    2 => array:18 [▶]
    3 => array:18 [▶]
    4 => array:18 [▶]
    5 => array:18 [▶]
    6 => array:18 [▶]
    7 => array:18 [▶]

I need to convert it into Laravel collection so instead of original json_decode I have to use:

$users = collect(array_values(json_decode($users, true))[1]);

It works, but I felt that this is not the right way to do that? Also, I have to use [1] at the end. What's if the array is empty and [1] does not exist? Do I need to validate if it exists or if there is a proper way to deal with this conversion?

Upvotes: 0

Views: 594

Answers (1)

becem
becem

Reputation: 116

After decoding the data you will have an associative array where you can access the data inside the 'value' array directly using $users['value'], so there is not need to use the array_values function.

$users = json_decode($users, true);
    if (isset($users['value'])) {
        $usersCollection = collect($users['value']);
    }

I guess something like this should work fine.

Upvotes: 1

Related Questions