1

How would I pluck an eager loading content while querying with Laravel 5.4?

I tried this way:

$something = Something::with(array('something_else' => function($query){
    $query->pluck('field');
}))->first();

And $query->select('field') too, but without luck. Is this possible in Laravel 5.4?

Luiz
  • 2,429
  • 8
  • 28
  • 43
  • Look here http://stackoverflow.com/questions/40635146/laravel-pluck-fields-from-relations – Scaffold Mar 17 '17 at 20:07
  • I would suggest taking a look at the query log so you can see how eloquent actually builds these queries. – lagbox Mar 18 '17 at 07:53

1 Answers1

3

You wouldn't be able to use pluck on the query but you can use select if you want to limit the fields returned with eager loading.

You just need to make sure you include the id so that Eloquent can match the relationships correctly e.g.:

$something = Something::with(array('something_else' => function($query){
    $query->select('id', 'field');
}))->first();

With Laravel >= 5.5, you can specify the columns you want included by appending : followed by a comma separated list of the fields. This means the above can be simplified to:

$something = Something::with('something_else:id,field')->first();

Please note that the related column fields need to be included for this to work i.e. the id for "belongs" relationships or *_id for "has" relationships (and *_type if polymorphic).

Rwd
  • 34,180
  • 6
  • 64
  • 78
  • 1
    I exactly want to hide the id. There is someway to workaround this? I have an entity with two fields: the id and the data. I want to serialize the data into an array like `['data1', 'data2', etc.]` – Luiz Mar 17 '17 at 22:17