ebeliejinfren
ebeliejinfren

Reputation: 312

How to get item from laravel eloquent collection by conditions?

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

Answers (2)

Rayann Nayran
Rayann Nayran

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

Collections - filter()

Upvotes: 2

IGP
IGP

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

Related Questions