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

devondahon's avatar

Query Builder ->first() to array instead of object

How to get the following query result into an array instead of an object ?

$res = DB::connection('myconn')->table('mytable')->where('MYID', $id)->first();
0 likes
4 replies
devondahon's avatar

@michaloravec Thanks for your help but I'd like to get this result into an array, not just take some rows from it. Also, ->first() returns an object of type stdClass, so functions like value() is undefined.

MichalOravec's avatar
Level 75

You mean like casting stdClass to the array?

$res = (array) DB::connection('myconn')->table('mytable')->where('MYID', $id)->first();
martinbean's avatar

How to get the following query result into an array instead of an object ?

@devondahon Heard of Eloquent? Heard of its toArray method?

Use it, instead of long-winded DB calls like this.

Please or to participate in this conversation.