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

phpMick's avatar
Level 15

Query builder to collection of models.

I had just made some changes to my database and now the relationships are more complicated.

This means that to get $user->reports I am now using the query builder to retrieve the reports which were previously just a many-to-many:

 $results = DB::table('users AS u')
            ->select('r.*')
etc

This means that I am now getting a collection of stdClass instead of a collection of models. Is there a way to use a query to get a collection of models (in one db hit).

I tried using hydrate but it requires an array.

Cheers,

Mick

0 likes
3 replies
kima's avatar

why not using

ModelClass::query()->select

?

if you want to use the hydrate function you can use it like

ModelClass::hydrate($results->toArray())
2 likes
phpMick's avatar
Level 15

Yeah, as soon as I had a coffee I got it:

$modelCollection = Report::hydrate($results->all()) ;

Cheers,

Mick

phpMick's avatar
Level 15

Not sure if I should make these function or accessors?

Please or to participate in this conversation.