Laravel 11 - How to Generate Sitemap

Touseef Afridi
24 Sep 24

Laravel 11 - How to Generate Sitemap

In this tutorial, we will discuss how to generate a sitemap in Laravel 10. A sitemap improves SEO by helping search engines index your site efficiently.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through creating and testing a sitemap for your Laravel project using the Spatie Sitemap package. It covers setting up a new Laravel project, installing the required package, and publishing the configuration. You’ll create views for the About and Contact pages, and then define routes for those pages and the sitemap generation route. The guide demonstrates how to manually generate the sitemap, add dynamic pages, and customize sitemap properties like frequency and priority. For the live environment, you can automate the sitemap generation by using a cron job.

Step # 1 : Set Up a New Laravel Project or Use an Existing One.

To get started, you have the option to either use an existing Laravel project or create a fresh one. If you have Laravel installed globally, you can quickly create a new project by running the following command:
laravel new sitemap
Alternatively, if you prefer using Composer, you can run this command:
composer create-project laravel/laravel --prefer-dist sitemap
During the setup process, you'll be prompted to make a few choices.
  • Starter Kit: Choose None for a clean Laravel installation without authentication scaffolding.
  • Testing Framework: Select Pest for a modern and expressive testing experience.
  • Database: Set MySQL as the database driver.
  • Migrations: Type yes to run default migrations and automatically set up the database tables.

This will create a new Laravel project named sitemap. If Laravel is installed globally, the laravel new command will quickly set up the project. If you're using Composer, it will download Laravel and its dependencies in the sitemap directory. The result is a clean Laravel installation without any starter kits, configured with Pest as the testing framework, MySQL as the database, and default migrations applied.

Step # 2 : Access the Project.

Open your terminal (such as Git Bash, Command Prompt, or Terminal) and navigate to the root directory of your Laravel project. To do this, run the following command in Git Bash.
cd c:xampp/htdocs/sitemap
This command will take you to the root folder of your Laravel project, where you can run Artisan commands and manage all the project's files. Ensure you're in the correct directory before proceeding with further setup or development tasks.

Step # 3 : Install the Spatie Laravel Sitemap Package.

To install the Laravel Sitemap package, run the following command in your terminal.
composer require spatie/laravel-sitemap
This command installs the Spatie Laravel Sitemap package, which allows you to easily generate sitemaps for your Laravel project. A sitemap is essential for search engine optimization (SEO) as it helps search engines crawl and index your site more effectively. By using this package, you can automate the creation of XML sitemaps for your website's pages. Additionally, the package provides flexibility in managing dynamic content and automatically updating the sitemap as your site grows or changes.

Step # 4 : Publish the Spatie Sitemap Configuration.

Publish the configuration using the following command.
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=sitemap-config
This command publishes the configuration file for the Spatie Laravel Sitemap package, making it possible to tailor various settings according to your needs. By publishing the configuration, you gain access to options for customizing important aspects of your sitemap, such as setting the update frequency, adjusting the priority of specific URLs, and determining how often search engines should revisit your pages. This flexibility allows you to fine-tune the sitemap to better suit your website’s structure, content update patterns, and SEO strategy, ultimately helping you optimize how your site is indexed by search engines.

Step # 5 : Create Views.

To test the sitemap functionality, create two views: about.blade.php and contact.blade.php.
For the about.blade.php file, add the following content.
<!DOCTYPE html>
<html>
<head>
 <title>About - Code Shotcut</title>
</head>
<body>
 <h1>About Page</h1>
 <p>Some description related to the about page.</p>
</body>
</html>
For the contact.blade.php file, use the following content.
<!DOCTYPE html>
<html>
<head>
 <title>Contact - Code Shotcut</title>
</head>
<body>
 <h1>Contact Page</h1>
 <p>Some description related to the contact page.</p>
</body>
</html>
These simple views simulate real pages on your site, helping test the sitemap functionality.

Step # 6 : Update web.php.

Define routes for the About and Contact pages, along with a route for generating the sitemap manually.
<?php
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
use Carbon\Carbon;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
Route::get('/', function(){
 return view('welcome');
});
Route::get('/about', function(){
 return view('about');
});
Route::get('/contact', function(){
 return view('contact');
});
Route::get('/sitemap', function () {
 //Lets generate sitemap manually
 $sitemap = Sitemap::create()
 ->add(Url::create('/'))
 ->add(Url::create('/about'))
 ->add(Url::create('/contact'));
 $sitemap->writeToFile(public_path('sitemap.xml'));
 return "success";
});
This setup defines routes for the About and Contact pages in your Laravel application, as well as a dedicated /sitemap route that will generate the sitemap. Once the sitemap is generated, it collects the URLs of the specified pages (such as the home, About, and Contact pages) and saves the sitemap in the public directory of your project as sitemap.xml. This makes it accessible for search engines and helps with better indexing of the site.

Step # 7 : It's time to test.

Start the Laravel development server by running the command.
php artisan serve
Let's generate the sitemap. Access the following URL: 127.0.0.1:8000/sitemap It should return success.

Now, let's view the sitemap.xml in the browser. Access the following URL: 127.0.0.1:8000/sitemap.xml.

You can add dynamic pages as follows.
Route::get('/sitemap', function () {
 $sitemap = Sitemap::create()
 ->add(Url::create('/'))
 ->add(Url::create('/about'))
 ->add(Url::create('/contact'));
 // Similarly you can add dynamic pages
 // For example dynamic pages for : Tags, Posts, Categories etc
 // For Dynamic pages.
 $posts = Post::all();
 foreach ($posts as $post) {
  $sitemap->add("/post/{$post->slug}");
 }
 $sitemap->writeToFile(public_path('sitemap.xml'));
 return "success";
});
Furthermore you can change frequency, priority etc.
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'));
});
For the live environment, you can create a cron job to automatically generate or update the sitemap.
This step allows you to test the sitemap generation, add dynamic pages, and customize the sitemap with frequency and priority settings, while also providing the option to automate the process in a live environment using a cron job.

Conclusion

By following this guide, you've successfully integrated sitemap generation into your Laravel project using the Spatie Sitemap package. Your application now generates a sitemap that helps search engines crawl and index your site more effectively. You’ve also learned how to add dynamic pages to the sitemap, customize its properties like frequency and priority, and automate the process for live environments using a cron job. This setup enhances your website's SEO and ensures that your pages are properly indexed.
For more details, please 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! 💸😄"
1

2 Comments

  • Mohammed profile image Mohammed
    29 Dec 24

    Thanks for this awesome guide, I would like to know to autogenerate method for this package.

    Mohammed profile avatar Touseef Afridi
    29 Dec 24

    You're welcome.
    For that you will have to create a command.
    php artisan make:command GenerateSitemap
    then update the GenerateSitemap like below.
    <?php
    namespace App\Console\Commands;
    use Illuminate\Console\Command;
    use Spatie\Sitemap\Sitemap;
    use Spatie\Sitemap\Tags\Url;
    use App\Models\Tag;
    class GenerateSitemap extends Command
    {
    protected $signature = 'sitemap:generate';
    protected $description = 'Generate the sitemap';
    public function handle()
    {
    // Define the static pages.
    $sitemap = Sitemap::create()
    ->add(Url::create(route('home')))
    ->add(Url::create('/about'))
    ->add(Url::create('/contact'));
    // Define the dynamic pages.
    $tags = Tag::all();
    foreach ($tags as $tag) {
    $sitemap->add(Url::create("/tag/{$tag->slug}"));
    }
    $sitemap->writeToFile(public_path('sitemap.xml'));
    }
    }
    Then register the GenerateSitemap command in Kernel.
    protected function schedule(Schedule $schedule)
    {
    // Generate sitemap on a daily basis
    $schedule->command('sitemap:generate')->daily();
    }
    Now you can execute the above command using a cron job/Supervisord (For live env) to run automatically.
    * * * * * php /path-to-your-project/artisan schedule:run
    This checks every minute for scheduled tasks and executes them.

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