I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item.
How can I achieve this?
@foreach($aboutcontent as $about)
<div class="col-md-4 text-center">
<div class="thumbnail">
<img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt="">
<div class="caption">
<h3>{{ $about->aboutname }}</h3>
<p>{{ $about->aboutinfo }}</p>
</div>
</div>
</div>
@endforeach
Possible duplicate of How to skip the 1st key in an array loop? As of Laravel 5.4, whenever you use foreach or for within blade files you will now have access to a $loop variable. The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration.
Use return to skip the loop and go to the next iteration in foreach Use forEach when you decided to go through all elements in the array no matter what happened. Use find when you decided to get the matching element from the array and ignore the rest. Thank you for reading. See you in the next article.
Update February 2018: In Laravel 5.3+ you can use $loop variable inside your blade loops. This variable holds useful information like current loop index and whether this is the first or last iteration through the loop. This is how you check for the first item:
The disadvantage is that you might need the first element within the same view, but that we don't know from your example. Note It might make more sense to remove the first element from the array before you pass on the data to the view. This will work in some cases, but usually you are iterating trough laravel collection not array...
There is two way to do this: 1- if your $key is numeric you can use:
@foreach($aboutcontent as $key => $about)
@if($key == 0)
@continue
@endif
code
@endforeach
2- if a $key is not numeric use @loop->first as a condition
As of Laravel 5.4, whenever you use foreach
or for
within blade files you will now have access to a $loop variable. The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration. See the example below, which is a much cleaner way of achieving the same result as the other older answers here:
@foreach ($rows as $row)
@if ($loop->first) @continue @endif
{{ $row->name }}<br/>
@endforeach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With