PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] How can I output the current iteration with Laravel's Paginate()?

 January 19, 2022     laravel, laravel-5.2, mysql, pagination, php     No comments   

Issue

Laravel 5.2 application.

I have a function in my controller that queries my DB with an order by clause to which I then paginate.

public function foo() {

  $results = DB::orderBy('name', 'desc')->paginate(15);
  return view('index', ['results' => $results]);

}

index.blade.php

@foreach ($results as $result)
 <tr>
  <td>{{ //current $result position is what I need }}</td>
  <td>{{ $result->name }}<td>
  //etc...
 </tr>
@endforeach

How could I output the current row order iteration?

e.g.

Rank | name | //page 1
1      bob  
2      john
3      katie
Rank | name | //page 2
4      dave  
5      michael
6      ruben

Usually I would just output the id but since I have an orderBy clause, the ID won't correctly reflect the current rank. And if I do something like a for() loop then when I go to the next page, it will reset the first result on the second page, to rank 1, even though it's the next page.

Does Laravel have a specific way of achieving this? I've looked through the docs and I'm unable to find what I'm looking for.


Solution

I was able to do this more elegantly than the suggestions provided via the firstItem() method.

public function foo() {

  $results = DB::orderBy('name', 'desc')->paginate(15);

  $rank = $results->firstItem();

  return view('index', ['rank' => $rank, 'players' => $players]);

}


index.blade.php

@foreach ($results as $result)
 <tr>
  <td>{{ $rank++ }}</td>
  <td>{{ $result->name }}<td>
  //etc...
 </tr>
@endforeach


Answered By - ProEvilz
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing