jlrdw's avatar
Level 75

Query Builder To Array work a round

In a post someone wanted some array results, I told them to add toArray after get:

->get()->toArray();

But I was using eloquent, they were using query builder. They got an array of objects.

I created an issue #27722 since I expected query builder would also work with toArray().

So you can read @mfn reply there, but bottom line if you want array from query builder:

Just a short example of both:

ORM works:

$dogs = Dog::where('adopted', '=', 0)->get()->toArray();

For query builder:

$data = DB::table('dc_dogs')->where('adopted', '=', 0)->get();
$dogs = collect($data)->map(function($x){ return (array)$x; })->toArray();

The cast and ->toArray() are needed. I had never needed or used this, but it just got me thinking about toArray not working the same. It has to do with Arrayable. I hope to array eventually works with query builder.

So if anyone needs toArray in query builder, I hope this helps.

0 likes
1 reply
jlrdw's avatar
Level 75
$dogarray = json_decode(json_encode($dogs), True);

Also works.

1 like

Please or to participate in this conversation.