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

cooperino's avatar

Separate query builder results to arrays

If I have a query that gives me collection with array of items (DB::table('items')->select('item_id', 'item_code'))

Illuminate\Support\Collection {#2992
  #items: array:2 [
    0 => {#2993
      +"item_id": 11
      +"item_code": "A1B2C3"
    }
    1 => {#2994
      +"item_id": 11343
      +"item_code": "A1B2C4"
    }
  ]
  #escapeWhenCastingToString: false
}

What would be the best way to separate the results to arrays of the fields?

so that I have array of item_ids and array of item_codes?

0 likes
1 reply
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

There are several ways. An easy way is to just

$data = DB::table('items')->select('item_id', 'item_code');
$ids = $data->pluck('item_id')->toArray();
$codes = $data->pluck('item_code')->toArray();
1 like

Please or to participate in this conversation.