Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output odd and even rows in laravel

Tags:

php

laravel

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:

  • Odd
  • Even
  • Odd
  • Even
like image 367
daugaard47 Avatar asked Feb 08 '19 18:02

daugaard47


2 Answers

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

like image 117
Khushbu Avatar answered Nov 09 '22 08:11

Khushbu


$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
like image 25
N Mahurin Avatar answered Nov 09 '22 09:11

N Mahurin