imperium2335
imperium2335

Reputation: 24122

Laravel remove first item in a collection

I want to remove the first item in a collection:

unset($productData->images->first())

The above doesn't work.

The reason I want this is so that later when I do a foreach, the first item doesn't come out:

@foreach($productData->images as $images)
    <img class="product-thumb" src="/images/products/{{$images->src_thumb}}">
@endforeach

How can this be done?

Upvotes: 26

Views: 30937

Answers (3)

Aleksandr Popov
Aleksandr Popov

Reputation: 520

In Laravel 5 you can use slice() method:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$slice = $collection->slice(4); 

$slice->all();    // [5, 6, 7, 8, 9, 10]

Upvotes: 11

Kostiantyn
Kostiantyn

Reputation: 1853

I do:

$first_key = $collection->keys()->first();
$collection = $collection->forget($first_key);

Upvotes: 6

lukasgeiter
lukasgeiter

Reputation: 152890

You can use shift() to get and remove the first item of a Laravel collection.
See the Source of Illuminate\Support\Collection

And here's an example:

$productData->images->shift();

Upvotes: 42

Related Questions