I have a project where I'm pulling posts from the database and rendering on the home page view. Like a Blog. (On the home page I limit this to 3 posts)
I have 6 rows in the table, and would like to style the output based on ODD and Even rows.
Here is my controller:
public function index()
{
$counter = Post::count();
$posts= DB::table('posts')->orderBy('id', 'DESC')->limit(3)->get();
return view('home',compact('posts','counter'));
}
I want the even numbered rows to have <div class="even">
and the odd numbered rows to have <div class="odd">
When I dd
on $counter
I get the value 6. This is correct. I have 6 rows in the table.
What I'm currently trying based on other articles I've found:
@foreach ($posts as $post)
@if($counter % 2 == 0)
<div class="even">{{$post->title}}</div>
@else
<div class="odd">{{$post->title}}</div>
@endif
This doesn't do anything. Still outputs the rows as 6,5,4,3,2,1
So how can I write the IF Statement inside my Foreach loop to say...
if ($counter == odd)
<div class="odd">
else
<div class="even">
The order I'm looking for is:
Laravel 5.8.5 add even and odd Boolean flags in the Blade loop variable
Now you can use:
$loop->even or $loop->odd
Instead of
$loop->iteration % 2
Reference link
$counter
is a static variable, so calling $counter % 2 == 0
will always show the same result.
If you are using Laravel 5.4+, there is a $loop
variable included in the @foreach()
. So you can access your mod division within the loop.
Here is the example for Laravel 5.4+
@foreach ($posts as $post)
@if($loop->iteration % 2 == 0)
<div class="even">{{$post->title}}</div>
@else
<div class="odd">{{$post->title}}</div>
@endif
@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