0
votes

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']);
2
Use filter method. It's in the documentation.IGP
Is $post->files a relationship?simonhamp

2 Answers

2
votes

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);
});
1
votes

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();

Collections - filter()