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

Moenchfracht's avatar

Select columns from query

Hi, I have a query with relations: \App\Products::where('xfs', '>',10)->with('users')->get() I know the select method to get only specific columns. But this only returns columns from the Products model. How can I get specific columns from the User model? Thanks!

0 likes
8 replies
Vilfago's avatar
Vilfago
Best Answer
Level 20
\App\Products::where('xfs', '>',10)
  ->with(['users' => function($q){
    $q->select('id', 'email', 'name'); //you have to select the relation column
  }])->get()
Vilfago's avatar

Forgot something, my code will not work ;)

You need to have the key and foreign key of the relation, so in this case id should be selected. Unless, Eloquent cannot reorganise data fetched.

I update the answer above

Moenchfracht's avatar

@VILFAGO - Hehe. Thanks, I tried it and accidentally I tried it with the ids before i read your update.

Another question concerning this: Is it possible to "flatten" this collection into one dimension? I know there's a flattenmethod for collections, but that doesn't work as expected. :( I need the data to export it to a csv and I don't know how to handle this multidimension collection.

Vilfago's avatar

If you want a flat result, you better use a join than an eloquent relation

Vilfago's avatar

These are not arrays, but instance of Model

Please or to participate in this conversation.