Home / Snippets / How to Generate Laravel Sitemaps with Spatie Sitemap Package
How to Generate Laravel Sitemaps with Spatie Sitemap Package cover

How to Generate Laravel Sitemaps with Spatie Sitemap Package

3.4K

3 years ago

0 comments

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
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this