How to Generate dynamic sitemap in Laravel 10 Step by Step

How to Generate dynamic sitemap in Laravel 10 Step by Step

Step 1: Install Spatie Laravel Sitemap Package

Firstly, you need to install the Spatie Laravel Sitemap package using Composer. You can do this by running the following command in your terminal:

composer require spatie/laravel-sitemap

Step 2: Publish the Package

The next step is to publish the package.You can do this by running the following command in you terminal:

php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=sitemap-config

A sitemap.php file will generate after this command where you can modify option based on you needs.

sitemap-file

Step 3: Make a command for generating Sitemap dynamic

The next step is to Generate a command for creating sitemap for your website .You can do this by running the following command in you terminal:

php artisan make:command GenerateSitemap

After this command a file will generate in app/console/commands/GenerateSitemap.php

Go to that file and paste the code under handle function and make sure you change the model name as yours.

$postsitmap = Sitemap::create();

        Blog::get()->each(function (Blog $post) use ($postsitmap) {

            $postsitmap->add(

                Url::create("/{$post->slug}")

                    ->setPriority(0.9)

                    ->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY)

           );

        });

      $postsitmap->writeToFile(public_path('sitemap.xml'));

Step 4: Test the command

Now we will test the command for generating sitemap. You can do this by running the following command in you terminal:

php artisan $signature

This $signature will be in that command file GenerateSitemap.php.

After this command you will get sitemap generated for you website is in public folder.

sitemap

Note: If you want to run this command daily, hourly or monthlyfor generating sitemap you can go to app/console/kernel.php file in that there is a function called Schedule put the below code in that function and change the time according to your needs.

$schedule->command('sitemap:generate')->daily();

Leave a comment