Mohamed Benhida

December 8, 2017

Custom Laravel Pagination

Laravel provide an eloquent helper called pagination but we need to add a page parametre in link like ?page=X.In this post we want to make change the parametre to /page/X.

We create a PostController using artisan command : php artisan make:controller PostController


    'uses' => 'PostController@index'
    'uses' => 'PostController@pagination',
    'as' => 'paginatePost'


We have something called Closure that gives the permission to pass a function as a parametre.

We have a function that returns a static currentPageResolver variable you can check in onvendor/laravel/framework/src/Illuminate/Pagination

public static function currentPageResolver(Closure $resolver)
        static::$currentPageResolver = $resolver;


    public $page;
    public $perpage = 2;

    public function paginator() {
        Paginator::currentPageResolver(function() {
            return $this->page;

        return Post::paginate($this->perpage);

    public function pagination($page) {

        $this->page = $page;

        $posts = $this->paginator();

        if($this->page > $post->lastPage())
            $this->page = $post->lastPage();

            return $this->paginator();

        return $posts;

we can make also our own html pagination but also laravel provides the default bootstrap pagination using links() method



@foreach($posts as $post)
{{ $post->title }}

@if ($posts->hasPages())
              <ul class="pagination">
                      {{-- Previous Page Link --}}
                      @if ($posts->onFirstPage())
                          <li class="disabled"><span>&laquo;</span></li>
                          <li><a href="{{ route("paginatePost",1) }}" rel="Previous">&laquo;</a></li>

                      {{-- Pagination Elements --}}
                      @for ($i=1; $i <= $posts->lastPage(); $i++)
                        @if ($i == $posts->currentPage())
                            <li class="active"><a href="#">{{ $i }}</a></li>
                            <li><a href="{{ route("paginatePost",$i) }}">{{ $i }}</a></li>
                      {{-- Next Page Link --}}
                      @if ($posts->hasMorePages())
                          <li><a href="{{ route("paginatePost",$posts->lastPage()) }}" rel="Next">&raquo;</a></li>
                          <li class="disabled"><span>&raquo;</span></li>

I Hope you enjoyed reading this post.

© Mohamed Benhida.

Blog | Packages | About