Posts Learn Components Snippets Categories Tags Tools About

How to Generate Laravel Sitemaps with Spatie Sitemap Package

Learn how to generate a sitemap with ease using the Spatie Sitemap generator package. Get to know how to instantly generate a sitemap for your website with one line of code.

Created on Sep 29, 2021


In this short snippet, you will learn how to easily generate a sitemap using a package called Laravel Sitemap by Spatie. The steps are very simple so let's get started.

Step 1: Install Laravel Sitemap by Spatie

Firstly do Install the package using Composer package manager to your Laravel project.
composer require spatie/laravel-sitemap

Step 2: Generate Sitemap

The next step is to call the SitemapGenerator class to generate the sitemap. This class has a static method called "create" which accepts the URL to crawl. To save the sitemap you can chain the method with "writeToFile" and pass in the path.

Route::get('generate-sitemap', function () {
The path can be the public storage so it's accessible right aways from the browser.

Route::get('generate-sitemap', function () {
Now you can access the "sitemap.xml" from your code editor or from the browser directly to see the generated sitemap.

Step 3: Update robots.txt

Before pushing your code to production do make sure to update the "robots.txt" to specify the location of the sitemap.
User-agent: *

Sitemap: https://app.test/sitemap.xml
By doing that you will let search engines crawler locate the location of the sitemap and enable it to crawl your site links.

Optional: Sitemap Configuration File

You may publish the sitemap configuration file and from the config, you can specify how long the timeout of the crawler request and etc.
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=config
The location of the configuration will be inside the config directory.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️