phplaravelseositemap

How do I implement pagination support in laravel-seo-sitemap?


I'm using the laravel-seo-sitemap package to generate sitemap XML files in a Laravel 10 application.

I have a paginated blog route like this:

Route::prefix('/blog')->group(function () {
    Route::get('/', [BlogController::class, 'index'])
        ->name('support.blog.index')
        ->priority('0.6')
        ->sitemap();
});

This correctly adds /blog to the sitemap, but I also want to include paginated versions like /blog?page=2, /blog?page=3, etc., since those contain unique and crawlable content (e.g. paginated archive listings).

How can I configure the package to generate sitemap entries for each page of the pagination?

Ideally, I'd like to specify:

Is there a way to extend the sitemap generator with a custom SitemapItemTemplate or hook into the route’s sitemap registration?

https://github.com/VeiligLanceren-nl/laravel-seo-sitemap

I already did try to use the template but it didn't work out as wished.


Solution

  • First of all, thanks for using my package. Based on your question I've made it easier in the package to use it with default Laravel pagination. The trait is available in the 2.1.0 version I just released. Below are two examples for generating paginated sitemap entries in a custom sitemap template:

    1. Without using the HasPaginatedSitemap Trait

    You can handle pagination logic manually in your template without using the trait:

    use Illuminate\Routing\Route;
    use VeiligLanceren\LaravelSeoSitemap\Sitemap\Item\Url;
    
    class BlogIndexTemplate implements SitemapItemTemplate
    {
        public function generate(Route $route): iterable
        {
            $totalItems = Post::published()->count();
            $perPage = 20;
            $totalPages = (int) ceil($totalItems / $perPage);
    
            for ($page = 1; $page <= $totalPages; $page++) {
                // If you want to skip page=1 in the query, handle it here
                // if ($page === 1) continue;
    
                $url = route($route->getName(), ['page' => $page]);
                yield Url::make($url);
            }
        }
    }
    

    2. With the HasPaginatedSitemap Trait

    Pagination logic is encapsulated in the trait, reducing boilerplate and preventing mistakes:

    use Illuminate\Routing\Route;
    use VeiligLanceren\LaravelSeoSitemap\Support\Traits\HasPaginatedSitemap;
    
    class BlogIndexTemplate implements SitemapItemTemplate
    {
        use HasPaginatedSitemap;
    
        public function generate(Route $route): iterable
        {
            $totalItems = Post::published()->count();
            $perPage = 20;
    
            // Optionally, pass true as last argument to skip page=1 in the query string
            yield from $this->paginatedUrls($route, $totalItems, $perPage);
        }
    }
    

    Benefits of using the Trait: