Posts Learn Components new Snippets new Categories Tags 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

339 views

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.
<?php

Route::get('generate-sitemap', function () {
    SitemapGenerator::create('https://app.test')
        ->writeToFile($path);
});
The path can be the public storage so it's accessible right aways from the browser.
<?php

Route::get('generate-sitemap', function () {
    SitemapGenerator::create('https://app.test')
        ->writeToFile(public_path('sitemap.xml'));
});
Now you can access the "sitemap.xml" from your code editor or from the browser directly to see the generated sitemap.
https://app.test/sitemap.xml

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: *
Disallow:

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.
config/sitemap.php
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻