Blum
Blum

Reputation: 899

How can I get get elements by array of keys from a collection?

I have a collection (for example with 10 elements), I want to do make out another collection of elements of just two elements with ids of 5 and 6. Something like that:

$newCollection = $collection->get([5,6]);

$collection is an instance of Illuminate\Database\Eloquent\Collection. But of course I get error:

The first argument should be either a string or an integer

I know I can make it with cycle or closures, I just wandering if there is more elegant way. Can not find such thing in the documentation. This is for laravel 5.

Thanks

Upvotes: 0

Views: 723

Answers (3)

Chris
Chris

Reputation: 58142

You can use Collection::only.

For example:

$collection->only([5, 6]);

Note that it looks at the attribute primary key to know which key to work against. For example, if returning a database collection, $collection->primaryKey will most likely be 'id'.

Upvotes: 2

Raviraj Chauhan
Raviraj Chauhan

Reputation: 653

Simple, use whereIn()

$newCollection = $collection->whereIn('id', [5, 6])->get();

OR

Directly using eloquent model:

$newCollection = Collection::whereIn('id', [5, 6])->get();

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212402

Using a filter perhaps, assuming these are id values:

$idList = [5,6];
$newCollection = collection->filter(
    function($value) use ($idList) {
        if (in_array(value->id, $idList) {
            return true;
        }
    }
);

Upvotes: 1

Related Questions