1

How would I pluck relation of eager loading, while querying with Laravel 5.2?

$users = User::with(['posts' => function($query){
       $query->pluck('id');
       }])->get();

I want the response to be just the numbers of user's posts ids, like this:

[{user: Blabel, posts: [24,25,26]},
 {user: Kraker, posts: [75,76,77]}]

What I'm getting now, are all the fields from posts table:

[{user:Blabel,
  posts:[{id:24, name: "blabla", text: "bleble"},
         {id:25, name: "blablabla", text: "blebleble"},
         {id:26, name: "blablablo", text: "blebleblo"},
         ...
        ]},
  {user:Kraker,
   posts:[{id:75, name: "krakra", text: "krekre"},
          {id:76, name: "krakrakra", text: "krekrekre"},
          {id:77, name: "krokro", text: "krekrekro"},
          ...
         ]}

Can I use pluck in Eager Loading Constraint? It is the same question as: Pluck Eager Loading Laravel 5.4 , but I didn't find the successful answer.

Charles_IV
  • 13
  • 4
  • Possible duplicate of [Laravel pluck fields from relations](https://stackoverflow.com/questions/40635146/laravel-pluck-fields-from-relations) – Oluwafemi Sule Feb 20 '18 at 20:49
  • Thank you, but I need to pluck only the values in the relation, not all the query. I updated my question. – Charles_IV Feb 23 '18 at 12:42

1 Answers1

1

You have to pluck the ids after the query:

$users = User::with(['posts' => function($query){
   $query->select('id', 'user_id'); // assuming it's a HasMany relationship
}])->get();
$users = $users->toArray();
foreach($users as $i => $user) {
    $users[$i]['posts'] = collect($user['posts'])->pluck('id');
}
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109