Reputation: 41
$reviews has 10 arrays and I am trying to only display the first 5. This is what I have come up so far.
@for ($i = 0; $i < 6; $i++)
@foreach ($reviews as $reviews; i++)
<p>Body</p>
@endforeach
@endfor
Any idea why this isn't working?
Upvotes: 0
Views: 3768
Reputation: 1325
You have written the wrong syntax of foreach
<?php $i = 1; ?>
@foreach ($reviews as $review)
<p>Body</p>
@if ($i == 5)
break;
@endif
<?php $i++; ?>
@endforeach
Upvotes: 0
Reputation: 6565
You can use @if
to limit the loop inside @foreach
@for ($i = 0; $i < 6; $i++)
@foreach ($reviews as $review)
{{$i++}}
@if ($i < 1)
<p>Body</p>
@endif
@endforeach
@endfor
Upvotes: 0
Reputation: 1164
As you are asking .
Any idea why this isn't working?
Because you have syntax error here i++
@for ($i = 0; $i < 6; $i++)
@foreach ($reviews as $key=>$values)
<p>{{$i}} : Body</p>
@endforeach
@endfor
Note : changed $reviews
row value as $values
Upvotes: 0
Reputation: 359
Just use the take method and run a foreach loop, like so
@foreach($reviews->take(5) as $review)
<p>{{ $review->body }}</p>
@endforeach
I think that is much simpler and cleaner
Upvotes: 8
Reputation: 9442
Assuming you are using Collections
you could use the take
method (see here) method:
$collection = collect([0, 1, 2, 3, 4, 5]);
$chunk = $collection->take(3);
$chunk->all();
// [0, 1, 2]
Usage
$reviews2 = $reviews->take(5);
@foreach ($reviews2 as $review)
<p>{{ $review->body }}</p>
@endforeach
Upvotes: 3