Reputation: 331
My code currently looks like this:
foreach ($things as $thing) {
$ids[] = $thing->id;
}
dd(Other::whereIn('thing_id', $ids)->get());
Thing model has many Other
public function others()
{
return $this->hasMany(Other::class);
}
It's working, but can I achieve this functionality without using the foreach? It doesn't seems to be clean for me. I've tried to give whole collection to where in like this:
dd(Other::whereIn('thing_id', $things)->get());
but this only returned where id was 1.
I'm looking for help to clean up this code, any help appreciated.
Upvotes: 0
Views: 1290
Reputation: 628
There is a function called "pluck"
You can apply it on a collection as following
$collection->pluck('id');
More can be seen on docs
https://laravel.com/docs/7.x/collections#method-pluck
Upvotes: 3
Reputation: 331
I've already found a way to clean it up a bit, instead of foreach I can simply use :
$ids=$things->pluck('id');
If there's a cleaner way pls show me :)
Upvotes: 0