Laravel Sitemap: Generate One with spatie/laravel-sitemap
Laravel does not generate a sitemap automatically. The most widely used solution is the spatie/laravel-sitemap package, which provides a fluent API for building sitemaps programmatically. Install via Composer: composer require spatie/laravel-sitemap
Installation and Basic Usage
Create a controller that builds and returns the sitemap as an XML response:
Generating URLs from Database Models
For dynamic content like blog posts, loop over your models and add a URL for each:
Caching the Sitemap
For large sites, generating the sitemap on every request is expensive. Wrap sitemap generation in Cache::remember with a TTL of several hours. Invalidate the cache in model observers when content is published or updated so the sitemap stays fresh.
Common Laravel Sitemap Issues
APP_URL not set correctly: If APP_URL in your .env is set to localhost or a staging URL, all sitemap URLs will use the wrong base domain. Set APP_URL to your production domain in your production environment configuration.
Memory limit on large catalogs: Fetching millions of product URLs in one query will exhaust memory. Use chunk() or lazy() instead of all() when iterating over large model collections.
Related Guides
- WordPress Sitemap: Setup, Fix, and Submit Guide
- Shopify Sitemap: Location, Errors, and How to Submit It
- Wix Sitemap: How It Works and How to Submit It
- Squarespace Sitemap: How It Works and Common Fixes
- Webflow Sitemap: How It Works and How to Submit It
- Drupal Sitemap: XML Sitemap Module Setup Guide
- Fix Sitemap for Laravel