'Blade Foreach alternating classes
I am using a blade template and I was wanting to know within my foreach what the best way is for me to have it so that my first .panel-heading has another class added to it and then the second one has another etc
Example:
.red
.blue
.red
.blue
.red
Code:
@foreach ($dealsDB as $deal)
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="fa fa-fw fa-gift"></i>{{ $deal->title }}</h4>
</div>
<div class="panel-body">
<p>{{ $deal->content }}</p>
</div>
</div>
</div>
@endforeach
Solution 1:[1]
You can use @switch inside your @foreach to assign different class on every iteration.
@foreach (...)
<div class="
@switch($loop->iteration)
@case(1)
red
@break
@case(2)
green
@break
@case(3)
blue
@break
@default
yellow
@endswitch
">
@endforeach
Solution 2:[2]
In Laravel 5.8+, the $loop->odd or $loop->even variables can be used for this.
Furthermore, in Laravel 8.0 the @class directive was added. This is the perfect use case example for it.
In Laravel 5.3+ there is the $loop->iteration which returns the current loop iteration (starts at 1).
Docs:
https://laravel.com/docs/5.8/blade#the-loop-variable
https://laravel.com/docs/8.x/blade#conditional-classes
The following examples will return the exact same result.
Laravel 8+ version
@foreach ($dealsDB as $deal)
<div class="col-md-4">
<div @class([
'panel panel-default',
'red-class' => $loop->odd,
'blue-class' => $loop->even
])>
<div class="panel-heading">
<h4><i class="fa fa-fw fa-gift"></i>{{ $deal->title }}</h4>
</div>
<div class="panel-body">
<p>{{ $deal->content }}</p>
</div>
</div>
</div>
@endforeach
Laravel 5.8+ Version
@foreach ($dealsDB as $deal)
<div class="col-md-4">
<div class="panel panel-default
@if($loop->odd) red-class @else blue-class @endif">
<div class="panel-heading">
<h4><i class="fa fa-fw fa-gift"></i>{{ $deal->title }}</h4>
</div>
<div class="panel-body">
<p>{{ $deal->content }}</p>
</div>
</div>
</div>
@endforeach
Laravel 5.3+ Version
@foreach ($dealsDB as $deal)
<div class="col-md-4">
<div class="panel panel-default
@if($loop->iteration % 2 == 0) blue-class @else red-class @endif">
<div class="panel-heading">
<h4><i class="fa fa-fw fa-gift"></i>{{ $deal->title }}</h4>
</div>
<div class="panel-body">
<p>{{ $deal->content }}</p>
</div>
</div>
</div>
@endforeach
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Cornel Raiu |
