Skip to content
Advertisement

Decrementing row count with Laravel pagination (not Incrementing)

I want to display the row count of a decrementing paginated collection in Laravel, I have searched a lot, and there are methods to do it incrementing order, but not decrementing.

Explaining the issue:

Using Laravel 8.x, I have a controller method like this (simplified):

public function page(){
    // Please note the orderBy('id','DESC')
    $info = ModelName::where('something','value')->orderBy('id','DESC')->paginate(5);
    return view('page', compact('info'));
}

In my view, I display the data in a table like this

<tr>
    <th>#</th>
    <th>Name</th>
</tr>
@foreach($info as $item)
  <tr>
      <td>{{ $info->firstItem() + $loop->index; }}</td> /* <--- This is where I need help */
      <td>{{ $item->name }}</td>
  </tr>
@endforeach

And finally the pagination links

{{ $info->links() }}

Currently, even though I have a orderBy('id','DESC') and the first result in table is actually the last data, I am displaying the row count (#) in table like this:

Page 1:

------------------------------
|  #   |         Name        |
------------------------------
|   1  |        Value J      |
|   2  |        Value I      |
|   3  |        Value H      |
|   4  |        Value G      |
|   5  |        Value F      |
------------------------------

Page 2:

------------------------------
|  #   |         Name        |
------------------------------
|   6  |        Value E      |
|   7  |        Value D      |
|   8  |        Value C      |
|   9  |        Value B      |
|  10  |        Value A      |
------------------------------

But what I want to do is to display the row count in reverse

Because first result displayed is actually the last result (orderBy('id','DESC')).

Like this:

Page 1:

------------------------------
|  #   |         Name        |
------------------------------
|  10  |        Value J      |
|   9  |        Value I      |
|   8  |        Value H      |
|   7  |        Value G      |
|   6  |        Value F      |
------------------------------

Page 2:

------------------------------
|  #   |         Name        |
------------------------------
|   5  |        Value E      |
|   4  |        Value D      |
|   3  |        Value C      |
|   2  |        Value B      |
|   1  |        Value A      |
------------------------------

How can I achieve this?

P.S. I cannot just use the ID, as there are gaps in between results because of the WHERE clause.

Advertisement

Answer

In case any one else needs to do this, here is the solution:

{{ ($info->total() - ($info->firstItem() + $loop->index)) + 1 }}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement