Skip to content

Instantly share code, notes, and snippets.

@MostafaEzzelden
Forked from paulofreitas/custom-paginator.md
Created March 2, 2020 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostafaEzzelden/33a1e97f1c9c8a558f43a8dd65ffc10b to your computer and use it in GitHub Desktop.
Save MostafaEzzelden/33a1e97f1c9c8a558f43a8dd65ffc10b to your computer and use it in GitHub Desktop.
Custom Google-like length-aware paginator for Laravel 5.4+
  • Save the helpers.php file in your app directory
  • Edit your composer.json manifest file to auloload this file:
    "autoload": {
        "files": [
            "app/helpers.php"
        ],
    // ...
  • Execute the composer dump command to update the autoloaded files
  • Execute the php artisan vendor:publish --tag=laravel-pagination command to publish the pagination views
  • Save the custom.blade.php file in the resources/views/vendor/pagination directory
  • Use it like that: User::paginate(10)->links('pagination::custom')
@if ($paginator->hasPages())
<ul class="pagination">
{{-- Previous Page Link --}}
@if ($paginator->onFirstPage())
<li class="disabled"><span>&laquo;</span></li>
@else
<li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">&laquo;</a></li>
@endif
{{-- Pagination Elements --}}
@foreach (pagination_links($paginator, 10) as $page => $url)
@if ($page == $paginator->currentPage())
<li class="active"><span>{{ $page }}</span></li>
@else
<li><a href="{{ $url }}">{{ $page }}</a></li>
@endif
@endforeach
{{-- Next Page Link --}}
@if ($paginator->hasMorePages())
<li><a href="{{ $paginator->nextPageUrl() }}" rel="next">&raquo;</a></li>
@else
<li class="disabled"><span>&raquo;</span></li>
@endif
</ul>
@endif
<?php
use Illuminate\Contracts\Pagination\Paginator;
function pagination_links(Paginator $paginator, $pageSize = 10)
{
$currentPage = $paginator->currentPage();
$lastPage = $paginator->lastPage();
$startPage = 1;
$endPage = $lastPage;
$middlePageSize = ceil($pageSize / 2);
$oddPageSize = (bool) $pageSize & 1;
if ($lastPage > $pageSize) {
if ($currentPage <= ($oddPageSize ? $middlePageSize : $middlePageSize + 1)) {
$endPage = $pageSize;
} elseif ($currentPage + ($middlePageSize - 1) >= $lastPage) {
$startPage = $lastPage - ($pageSize - 1);
} else {
$startPage = $currentPage - ($oddPageSize ? $middlePageSize - 1 : $middlePageSize);
$endPage = $currentPage + ($middlePageSize - 1);
}
}
return collect(range($startPage, $endPage))->mapWithKeys(function ($page) use ($paginator) {
return [$page => $paginator->url($page)];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment