Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DuikGek's avatar

foreach grab the first 5 elements

Is there a way i can get the first 5 element (comments) of a foreach

 @foreach($comments as $comment)
                <p>Name user: {{$comment->name}}</p>
                <p>Comment: {{$comment->comment}}</p>
            @endforeach
0 likes
5 replies
Snapey's avatar
Snapey
Best Answer
Level 122
 @foreach($comments->take(5) as $comment)
                <p>Name user: {{$comment->name}}</p>
                <p>Comment: {{$comment->comment}}</p>
            @endforeach
4 likes
RushVan's avatar

How could you use this to take only the items AFTER the first 5?

Snapey's avatar

@RushVan $comments->slice(5) if already working with a collection, or you can use skip in a database query

Please or to participate in this conversation.