Mohamed Benhida

admin@devma.net

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

routes/Web.php

Route::get('/posts',[
    'uses' => 'PostController@index'
]);
Route::get('/posts/page/{page}',[
    '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;
    }

PostController.php

    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

$posts->links();

home.blade.php

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

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

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

I Hope you enjoyed reading this post.

© Mohamed Benhida.

Blog | Packages | About