Reputation: 312
I use laravel eloquent to get files of post that give me a collection
but I want an item from that collection by condition.
For example from that collection I want an item that type = 'product'
.
I am using foreach and check every item that have my condition and return it, but isn't any better way?
I tested collection method like contain but it return null
.
Files item have type filed that value is 'product' or 'blog'.
My code:
$post= Post::where('slug' , $slug)->first();
$cover = $post->files->contains(['type' , '=' , 'product']);
Upvotes: 0
Views: 2039
Reputation: 1135
The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:
$filtered = $post->files->filter(function ($value, $key) {
return $value->type == 'product';
});
$filtered->all();
Upvotes: 2
Reputation: 15909
Use the collection filter
method.
$cover = $post->files->filter(function($file) {
// show only the items that match this condition
return collect(['product', 'blog'])->contains($file->type);
});
Upvotes: 3