Anibal Cardozo
Anibal Cardozo

Reputation: 83

Laravel take from collection with offset

I got this collection

$collection = collect([0, 1, 2, 3, 4, 5]);

I know I can use the method take() to bring the X first elements of the collection

$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]

But I was wondering, if is there a way to add an offset to the take() method or do something that produce a result like this

$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3,2);

$chunk->all();

// [2, 3, 4]

any clue?

Upvotes: 0

Views: 1373

Answers (3)

Pradeep
Pradeep

Reputation: 9717

The splice method removes and returns a slice of items starting at the specified index:

You may pass a second argument to limit the size of the resulting collection:

$collection = collect([0,1, 2, 3, 4, 5]);

$chunk = $collection->splice(2, 3);

dd($chunk->all());

you can also use slice method if you want retain all the the values in the collection for future use

For more : https://laravel.com/docs/8.x/collections#method-splice

Upvotes: 1

Amir
Amir

Reputation: 513

use skip method

$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->skip(2)->take(3);
$chunk->all();

Upvotes: 3

Robo Robok
Robo Robok

Reputation: 22703

Use slice() method instead of take()

Upvotes: 0

Related Questions