user7381027
user7381027

Reputation: 41

Laravel Only display first 5 array

$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

Answers (5)

Aman Maurya
Aman Maurya

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

Himanshu Upadhyay
Himanshu Upadhyay

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

freelancer
freelancer

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

larsbadke
larsbadke

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

ka_lin
ka_lin

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

Related Questions