erm_durr
erm_durr

Reputation: 537

Laravel 4 pagination count

I have set a pagination in my specific view/site, and it works.

The problem is I have a php counter:

<?php $count = 0;?> 
   @foreach ($players as $player)
    <?php $count++;?>
    <tr>
    <td>{{ $count }}. </td> 

and whenever I switch pages, it starts from 1.

How could I change that?

Upvotes: 4

Views: 5573

Answers (6)

user4413898
user4413898

Reputation: 1

Simple and elegant:

@foreach ($players as $key => $player)
    <tr>
        <td>{{ $players->getFrom() + $key }}</td>
    </tr>
@endforeach

Upvotes: 0

Octavian Ruda
Octavian Ruda

Reputation: 87

You don't need a counter.

After you get the key that starts from 0, you need to add 1. After that you add the current page-1 * items per page

You can do it like this:

@foreach ($players as $key => $player)
    <tr>
        <td>{{ $key+1+(($players->getCurrentPage()-1)*$players->getPerPage()) }}</td>
    </tr>
@endforeach

Upvotes: 0

Ifan Iqbal
Ifan Iqbal

Reputation: 3093

We only need method getFrom from Paginator instance to be able counting from the first item in the page.

<?php $count = $players->getFrom(); ?> 
@foreach ($players as $player)
    <tr>
        <td>{{ $count++ }}. </td>
    </tr>
@endforeach

Upvotes: 1

Ian Romie Ona
Ian Romie Ona

Reputation: 131

<?php echo "Displaying ".$data->getFrom() ." - ".$data->getTo(). " of ".number_format($data->getTotal())." result(s)"; ?>

Upvotes: 1

vFragosop
vFragosop

Reputation: 5773

In order to achieve that, you need to initialize the value of counter:

<?php $count = (($current_page_number - 1) * $items_per_page) + 1; ?>

Notice I'm first subtracting 1 from current page, so the first page number is 0. Then I'm adding 1 to the total result, so your first item starts with 1, instead of 0.

Laravel Paginator provides a handy shortcut for that:

<?php $count = $players->getFrom() + 1; ?>
@foreach ($players as $player)
    ...

There are a few others that you can use as you like:

$players->getCurrentPage();
$players->getLastPage();
$players->getPerPage();
$players->getTotal();
$players->getFrom();
$players->getTo();

Upvotes: 17

Abishek
Abishek

Reputation: 11691

<?php $count++; ?>
@if($players->getCurrentPage() > 1)
{{ ((($players->getCurrentPage() - 1)* $players->getPerPage()) + $count)}}
@else
{{$count}}
@endif

Upvotes: 0

Related Questions