pshitote's avatar

How do I use custom length aware paginator to replace ?page=1 to localhost?

Hi, I am implementing a custom length aware paginator in Laravel 10 and would like to remove or replace http://localhost/?page=1 to http://localhost instead. How can I achieve this using custom length aware paginator in Larave? I am still new to Laravel. Thanks

0 likes
6 replies
tisuchi's avatar

@pshitote You can use a custom pagination provider. For example:

<?php

namespace App\Providers;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class PaginatorServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::currentPathResolver(function () {
            /** @var LengthAwarePaginator $this */
            return $this->resolveCurrentPath();
        });

        Paginator::currentPageResolver(function ($pageName = 'page') {
            $page = $this->resolveCurrentPage($pageName);

            return $page == 1 ? null : $page;
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Now in your config/app.php add in the providers array:

'providers' => [
    // ...

    App\Providers\PaginatorServiceProvider::class,

    // ...
],

1 like
pshitote's avatar

@tisuchi I am getting the error: Call to undefined method App\Providers\PaginatorServiceProvider::resolveCurrentPage()

jlrdw's avatar

How would you have Pages after localhost only?

Wouldn't it be like, and just example:

http://localhost/ledger?page=1

Also in more detail exactly what are you trying to do only remove that if page is equal to one, what if there are other pages?

There are a couple of different GitHub packages that will do friendly urls.

Just my opinion but I would stick with out of the box pagination exactly as it is in documentation.

A query string for pagination does not affect SEO.

pshitote's avatar

@jlrdw I have an application that retrieves posts from a database and renders them on view with pagination and <link rel="prev" ...> and <link rel="next" ...> . Links to page 1 used in the pagination and link prev and next tags should never include page=1 as a parameter. The expected approach to handling this is to implement a custom length aware paginator that will provide a custom URL if the previous link is to page 1.

Please or to participate in this conversation.