Laravel 12 - How to Generate a Sitemap with Spatie.

Touseef Afridi
12 Mar 26

Laravel 12 - How to Generate a Sitemap with Spatie.

In this tutorial we will learn how to quickly set up a sitemap in Laravel 12 using Spatie. Perfect for beginners, it shows how to create pages, add routes, and generate sitemap.xml to boost your SEO.

Quick Overview

This guide walks you through creating and testing a sitemap for your Laravel project using the Spatie Sitemap package. You’ll start by setting up a fresh Laravel application, installing the package, and publishing its configuration. Next, you’ll create sample pages for About and Contact, and define routes for these pages along with a route to generate the sitemap manually. Finally, you’ll test the sitemap generation, learn how to include dynamic pages, customize properties like priority and change frequency, and set up automation for keeping the sitemap up to date in a live environment.

Step # 1 : Create a Fresh Laravel 12 Application.

To start, we need a clean Laravel 12 project. Working with a fresh installation helps keep the environment simple and avoids conflicts before we add the sitemap functionality. If you already have the Laravel Installer installed globally, you can quickly create a new project by running.
laravel new sitemap
If you prefer to use Composer, you can create the project with.
composer create-project laravel/laravel sitemap
When creating the project with Composer, the installation runs immediately without asking any setup questions. You can configure your environment later by updating the .env file. On the other hand, the Laravel Installer provides a short interactive setup where you can choose some initial configuration options. During that setup, use the following selections.
  • Starter Kit: Select None this keeps the project minimal without any authentication scaffolding.
  • Testing Framework: Select Pest a modern and developer friendly testing framework.
  • Database: Select MySQL as the database.
  • Run Migrations: Type Yes this will create the default database tables right away.
  • Frontend Dependencies: Choose Yes to install frontend dependencies automatically.

After the installation finishes, you’ll have a fresh Laravel 12 application ready to go. The project will include Pest for testing, MySQL configured as the database driver, frontend dependencies installed, and the default migrations already applied. This gives us a clean foundation to start implementing the sitemap feature.

Step # 2 : Navigate to the Project Directory.

After creating the project, open your terminal (Git Bash, Command Prompt, or Terminal) and move to the Laravel project folder by running.
cd c:xampp/htdocs/sitemap
This will take you to the root directory of the project, where you can run Artisan commands and continue the setup.

Step # 3 : Install the Spatie Sitemap Package.

Next, we’ll install a package that makes generating sitemaps in Laravel simple. Run the following command in your terminal.
composer require spatie/laravel-sitemap
This command installs the Spatie Laravel Sitemap package. It allows you to quickly generate XML sitemaps for your Laravel application, helping search engines discover and index your website’s pages more efficiently. The package also supports adding dynamic URLs, which is useful when your site includes content such as blog posts, products, or other database driven pages.

Step # 4 : Publish the Sitemap Configuration.

Next, publish the package configuration by running the following Artisan command.
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=sitemap-config
Publishing the configuration file gives you full control over how your sitemap works. You can customize important settings like update frequency, the priority of specific URLs, and how often search engines should revisit your pages. This flexibility makes it easy to fine tune your sitemap according to your website’s structure and content update patterns. By tailoring these settings, you help search engines index your site more effectively and ensure that your pages are always discoverable as your site grows.

Step # 5 : Create Sample Pages For Sitemap.

Before generating the sitemap, let's create a couple of simple pages that will later appear in our sitemap. First, create the about page inside: resources/views/about.blade.php. Then add the following content to the file.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>About - Code Shotcut</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-gray-200 min-h-screen flex items-center justify-center">
    <div class="max-w-2xl mx-auto p-8 bg-gray-800 rounded-xl shadow-lg">
        <h1 class="text-3xl font-bold mb-4">About Page</h1>
        <p class="text-gray-400">
            Some description related to the about page.
        </p>
    </div>
</body>
</html>
Next, create the contact page inside: resources/views/contact.blade.php. Add the following content.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact - Code Shotcut</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-gray-200 min-h-screen flex items-center justify-center">
    <div class="max-w-2xl mx-auto p-8 bg-gray-800 rounded-xl shadow-lg">
        <h1 class="text-3xl font-bold mb-4">Contact Page</h1>
        <p class="text-gray-400">
            Some description related to the contact page.
        </p>
    </div>
</body>
</html>
These pages will serve as example routes that we can later include in the sitemap.

Step # 6 : Define Routes in web.php.

Next, we need to define routes for the pages we created earlier. We’ll also add a route that allows us to generate the sitemap manually. Open routes/web.php and add the following code.
<?php
use Illuminate\Support\Facades\Route;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
// Home page
Route::get('/', function () {
    return view('welcome');
});
// About page
Route::get('/about', function () {
    return view('about');
});
// Contact page
Route::get('/contact', function () {
    return view('contact');
});
// Route to manually generate sitemap
Route::get('/sitemap', function () {
    $sitemap = Sitemap::create()
        ->add(Url::create('/'))
        ->add(Url::create('/about'))
        ->add(Url::create('/contact'));
    // Save sitemap.xml inside public directory
    $sitemap->writeToFile(public_path('sitemap.xml'));
    return "Sitemap generated successfully!";
});
Here we simply defined routes for the About and Contact pages. We also added a /sitemap route that generates the sitemap.xml file and stores it inside the public directory of the application. Once generated, the sitemap will include the URLs we added and can be accessed directly from the browser.

Step # 7 : Test the Spatie Sitemap.

Now it’s time to test everything and generate the sitemap. Start the Laravel development server by running the following command.
php artisan serve
Once the server is running, open your browser and visit: http://127.0.0.1:8000/sitemap. This route will generate the sitemap file and return a success message.

After that, you can view the generated sitemap by visiting: http://127.0.0.1:8000/sitemap.xml. You should now see the XML sitemap containing the URLs we added earlier.

Adding Dynamic Pages to the Sitemap:

In many applications, pages such as
blog posts, tags, or categories are generated dynamically. You can include those pages in your sitemap as well. For example, if you have a Post model, you can loop through the records and add them to the sitemap.
Route::get('/sitemap', function () {
    $sitemap = Sitemap::create()
        ->add(Url::create('/'))
        ->add(Url::create('/about'))
        ->add(Url::create('/contact'));
    // Example: adding dynamic post pages
    $posts = Post::all();
    foreach ($posts as $post) {
        $sitemap->add("/post/{$post->slug}");
    }
    $sitemap->writeToFile(public_path('sitemap.xml'));
    return "Sitemap generated successfully!";
});
This approach ensures that newly created posts or other dynamic pages can also be included in the sitemap.
Set Priority and Change Frequency: 

You can also customize
sitemap entries by defining properties such as priority, change frequency, and last modification date.
Route::get('/sitemap', function () {
    $sitemap = Sitemap::create()
        ->add(
            Url::create('/')
                ->setLastModificationDate(Carbon::yesterday())
                ->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
                ->setPriority(0.1)
        );
    $sitemap->writeToFile(public_path('sitemap.xml'));
});
These options help search engines understand how often a page changes and how important it is relative to other pages on your site.
Automating Sitemap Generation:

In a
production environment, it’s usually better to generate the sitemap automatically instead of doing it manually. This can be done by creating a cron job that periodically updates the sitemap file. Automating this process ensures that your sitemap stays up to date whenever new content is added to your site.

Conclusion

By following this guide, you've successfully integrated sitemap generation into your Laravel project using the Spatie Sitemap package. Your application can now generate a sitemap that helps search engines discover and index your pages more efficiently. You’ve also learned how to include dynamic pages and customize properties like priority and change frequency. For live environments, you have the option to automate sitemap generation using a cron job, ensuring your sitemap stays up to date as new content is added.
For more details and advanced options, you can refer to the Spatie Laravel Sitemap package documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering