Custom pagination view in Laravel 5

2020-01-24 10:58发布

Laravel 4.2 has the option to specify a custom view in app/config/view.php such as:

/*
|--------------------------------------------------------------------------
| Pagination View
|--------------------------------------------------------------------------
|
| This view will be used to render the pagination link output, and can
| be easily customized here to show any view you like. A clean view
| compatible with Twitter's Bootstrap is given to you by default.
|
*/
'pagination' => 'pagination_slider-alt'

This is gone in Laravel 5 at least regarding view.php.

Is there a way to replicate this behavior in Laravel 5?

19条回答
一夜七次
2楼-- · 2020-01-24 11:21

Hi there is my code for pagination: Use in blade @include('pagination.default', ['paginator' => $users])

Views/pagination/default.blade.php

@if ($paginator->lastPage() > 1)

si la pagina actual es distinto a 1 y hay mas de 5 hojas muestro el boton de 1era hoja --> if actual page is not equals 1, and there is more than 5 pages then I show first page button --> @if ($paginator->currentPage() != 1 && $paginator->lastPage() >= 5) << @endif
    <!-- si la pagina actual es distinto a 1 muestra el boton de atras -->
    @if($paginator->currentPage() != 1)
        <li>
            <a href="{{ $paginator->url($paginator->currentPage()-1) }}" >
                <
            </a>
        </li>
    @endif

    <!-- dibuja las hojas... Tomando un rango de 5 hojas, siempre que puede muestra 2 hojas hacia atras y 2 hacia adelante -->
    <!-- I draw the pages... I show 2 pages back and 2 pages forward -->
    @for($i = max($paginator->currentPage()-2, 1); $i <= min(max($paginator->currentPage()-2, 1)+4,$paginator->lastPage()); $i++)
            <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
            </li>
    @endfor

    <!-- si la pagina actual es distinto a la ultima muestra el boton de adelante -->
    <!-- if actual page is not equal last page then I show the forward button-->
    @if ($paginator->currentPage() != $paginator->lastPage())
        <li>
            <a href="{{ $paginator->url($paginator->currentPage()+1) }}" >
                >
            </a>
        </li>
    @endif

    <!-- si la pagina actual es distinto a la ultima y hay mas de 5 hojas muestra el boton de ultima hoja -->
    <!-- if actual page is not equal last page, and there is more than 5 pages then I show last page button -->
    @if ($paginator->currentPage() != $paginator->lastPage() && $paginator->lastPage() >= 5)
        <li>
            <a href="{{ $paginator->url($paginator->lastPage()) }}" >
                >>
            </a>
        </li>
    @endif
</ul>
查看更多
虎瘦雄心在
3楼-- · 2020-01-24 11:22

Here's one for Laravel 5, Bootstrap 4 and without Blade syntax (for those who find it infinitely harder to read).

To use, instead of:

{!! $users->render() !!}

Use:

@include('partials/pagination', ['paginator' => $users])

Where partials/pagination is your blade template file with the below contents pasted in.

// Number of links to show. Odd numbers work better
$linkCount = 7;
$pageCount = $paginator->lastPage();

if ($pageCount > 1)
{
    $currentPage = $paginator->currentPage();
    $pagesEitherWay = floor($linkCount / 2);
    $paginationHtml = '<ul class="pagination">';

    // Previous item
    $previousDisabled = $currentPage == 1 ? 'disabled' : '';
    $paginationHtml .= '<li class="page-item '.$previousDisabled.'">
                            <a class="page-link" href="'.$paginator->url($currentPage - 1).'" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                                <span class="sr-only">Previous</span>
                            </a>
                        </li>';

    // Set the first and last pages
    $startPage = ($currentPage - $pagesEitherWay) < 1 ? 1 : $currentPage - $pagesEitherWay;
    $endPage = ($currentPage + $pagesEitherWay) > $pageCount ? $pageCount : ($currentPage + $pagesEitherWay);

    // Alter if the start is too close to the end of the list
    if ($startPage > $pageCount - $linkCount)
    {
        $startPage = ($pageCount - $linkCount) + 1;
        $endPage = $pageCount;
    }

    // Alter if the end is too close to the start of the list
    if ($endPage <= $linkCount)
    {
        $startPage = 1;
        $endPage = $linkCount < $pageCount ? $linkCount : $pageCount;
    }

    // Loop through and collect
    for ($i = $startPage; $i <= $endPage; $i++)
    {
        $disabledClass = $i == $currentPage ? 'disabled' : '';
        $paginationHtml .= '<li class="page-item '.$disabledClass.'">
                                <a class="page-link" href="'.$paginator->url($i).'">'.$i.'</a>
                            </li>';
    }

    // Next item
    $nextDisabled = $currentPage == $pageCount ? 'disabled' : '';
    $paginationHtml .= '<li class="page-item '.$nextDisabled.'">
                            <a class="page-link" href="'.$paginator->url($currentPage + 1).'" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                                <span class="sr-only">Next</span>
                            </a>
                        </li>';

    $paginationHtml .= '</ul>';

    echo $paginationHtml;
}
查看更多
做自己的国王
4楼-- · 2020-01-24 11:22

beside the answer of @MantasD I would like to offer comprehensive customized Laravel pagination. Assuming using Laravel 5.2 and the following included view:

@include('pagination.default', ['pager' => $users])

Features

  • Showing Previous and Next buttons and disable them when not applicable
  • Showing First and Last page icon only if the Previous and Next page not doing the same
  • Generate relative links ex: (10, 100, 500 .. etc.) instead of limiting pages
  • Showing result from x to y of each page using a helper function.

default.blade.php

@if($pager->lastPage() != 1)
<ul class="pagination">

    @unless($pager->currentPage() < 3)
        <li class="paginate_button previous">
            <a href="{{ $pager->url(1) }}" title="First Page"><i class="fa fa-angle-double-left"></i></a>
        </li>
    @endunless

    <li class="paginate_button previous @unless($pager->previousPageUrl())disabled @endunless">
        <a href="{{ $pager->previousPageUrl() }}"><i class="fa fa-angle-left"></i></a>
    </li>

    @while($pager->paging++ < $pager->lastPage())
        @if (abs($pager->paging - $pager->currentPage()) >= 2)
            {{-- Generate relative links (eg. +10,etc) --}}
            @if(in_array(abs($pager->paging - $pager->currentPage()), array(10, 50, 100, 500, 1000))
            and $pager->paging != 1 and $pager->paging != $pager->lastPage())
                <li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
                    <a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
                        <!-- + {{ $pager->paging - $pager->currentPage() }} -->{{ $pager->paging }}
                    </a>
                </li>
            @endif
        @else
            <li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
                <a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
                    {{ $pager->paging }}
                </a>
            </li>
        @endif
    @endwhile

    <li class="paginate_button next @unless($pager->nextPageUrl())disabled @endunless">
        <a href="{{ $pager->nextPageUrl() }}"><i class="fa fa-angle-right"></i></a>
    </li>

    @unless($pager->lastPage() - $pager->currentPage() < 2)
        <li class="paginate_button next">
            <a href="{{ $pager->url($pager->lastPage()) }}" title="Last Page"><i class="fa fa-angle-double-right"></i></a>
        </li>
    @endunless

</ul>
@endif

PaginationStartEnd function

if (!function_exists('PaginationStartEnd')) {
function PaginationStartEnd($currentPage, $perPage, $total)
{
    $pageStart = number_format( $perPage * ($currentPage - 1));
    $pageEnd = $pageStart +  $perPage;

    if ($pageEnd > $total)
        $pageEnd = $total;

    $pageStart++;

    return array('start' => number_format($pageStart), 'end' => number_format($pageEnd));
}
}

You can use and customize this more as you wish.

Note: $pager->paging is variable set to 0 declared in the controller action

查看更多
老娘就宠你
5楼-- · 2020-01-24 11:22

I use this code with k7 theme and use this code with their built in class. You can also use this code with your theme and your class as you need..

try to do this.

<section class="page-paging pt-0">
  <div class="container">
    <div class="row">
      <div class="col-12">
        <nav aria-label="Page navigation example">
          @if ($view_post->lastPage() > 1)
            <ul class="pager list-inline mb-0 text-center">
              <li class="{{ ($view_post->currentPage() == 1) ? ' disabled' : '' }}p-1 list-inline-item float-sm-left">
                <a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url(1) }}">
                  <i class="fa fa-angle-left pr-1"></i> Prev
                </a>
              </li>
              @for ($i = 1; $i <= $view_post->lastPage(); $i++)
              <li class=" p-1 list-inline-item d-none d-md-inline-block">
                <a class="{{ ($view_post->currentPage() == $i) ? ' active' : '' }} page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($i) }}">{{ $i }}
                </a>
              </li>
              @endfor
              <li class="{{ ($view_post->currentPage() == $view_post->lastPage()) ? ' disabled' : '' }} p-1 list-inline-item float-sm-right">
                <a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($view_post->currentPage()+1) }}"> Next 
                  <i class="fa fa-angle-right pl-1"></i>
                </a>
              </li>
            </ul>
          @endif
        </nav>
      </div>
    </div>
  </div>
</section>
查看更多
Juvenile、少年°
6楼-- · 2020-01-24 11:23

In Laravel 5.3+ use

$users->links('view.name')

In Laravel 5.0 - 5.2 instead of

$users->render()

use

@include('pagination.default', ['paginator' => $users])

views/pagination/default.blade.php

@if ($paginator->lastPage() > 1)
<ul class="pagination">
    <li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
        <a href="{{ $paginator->url(1) }}">Previous</a>
    </li>
    @for ($i = 1; $i <= $paginator->lastPage(); $i++)
        <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
            <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
        </li>
    @endfor
    <li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
        <a href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
    </li>
</ul>
@endif

That's it.


If you have a lot of pages, use this template:

views/pagination/limit_links.blade.php

<?php
// config
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>

@if ($paginator->lastPage() > 1)
    <ul class="pagination">
        <li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
            <a href="{{ $paginator->url(1) }}">First</a>
         </li>
        @for ($i = 1; $i <= $paginator->lastPage(); $i++)
            <?php
            $half_total_links = floor($link_limit / 2);
            $from = $paginator->currentPage() - $half_total_links;
            $to = $paginator->currentPage() + $half_total_links;
            if ($paginator->currentPage() < $half_total_links) {
               $to += $half_total_links - $paginator->currentPage();
            }
            if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
                $from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
            }
            ?>
            @if ($from < $i && $i < $to)
                <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                    <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
                </li>
            @endif
        @endfor
        <li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
            <a href="{{ $paginator->url($paginator->lastPage()) }}">Last</a>
        </li>
    </ul>
@endif
查看更多
该账号已被封号
7楼-- · 2020-01-24 11:27

In Laravel 5 custom pagination is based on presenters (classes) instead of views.

Assuming in your routed code you have

$users = Users::paginate(15);

In L4 you used to do something like this in your views:

$users->appends(['sort' => 'votes'])->links();

In L5 you do instead:

$users->appends(['sort' => 'votes'])->render();

The render() method accepts an Illuminate\Contracts\Pagination\Presenter instance. You can create a custom class that implements that contract and pass it to the render() method. Note that Presenter is an interface, not a class, therefore you must implement it, not extend it. That's why you are getting the error.

Alternatively you can extend the Laravel paginator (in order to use its pagination logic) and then pass the existing pagination instance ($users->...) to you extended class constructor. This is indeed what I did for creating my custom Zurb Foundation presenter based on the Bootstrap presenter provided by Laravel. It uses all the Laravel pagination logic and only overrides the rendering methods.

With my custom presenter my views look like this:

with(new \Stolz\Laravel\Pagination($users->appends(['sort' => 'votes'])))->render();

And my customized pagination presenter is:

<?php namespace Stolz\Laravel;

use Illuminate\Pagination\BootstrapThreePresenter;

class Pagination extends BootstrapThreePresenter
{
    /**
     * Convert the URL window into Zurb Foundation HTML.
     *
     * @return string
     */
    public function render()
    {
        if( ! $this->hasPages())
            return '';

        return sprintf(
            '<ul class="pagination" aria-label="Pagination">%s %s %s</ul></div>',
            $this->getPreviousButton(),
            $this->getLinks(),
            $this->getNextButton()
        );
    }

    /**
     * Get HTML wrapper for disabled text.
     *
     * @param  string  $text
     * @return string
     */
    protected function getDisabledTextWrapper($text)
    {
        return '<li class="unavailable" aria-disabled="true"><a href="javascript:void(0)">'.$text.'</a></li>';
    }

    /**
     * Get HTML wrapper for active text.
     *
     * @param  string  $text
     * @return string
     */
    protected function getActivePageWrapper($text)
    {
        return '<li class="current"><a href="javascript:void(0)">'.$text.'</a></li>';
    }

    /**
     * Get a pagination "dot" element.
     *
     * @return string
     */
    protected function getDots()
    {
        return $this->getDisabledTextWrapper('&hellip;');
    }
}
查看更多
登录 后发表回答