Milind Daraniya

How to Automatically Generate Sitemap in Laravel?

Published July 30th, 2023 20 min read

A sitemap is a vital component for search engine optimization (SEO) as it helps search engines discover and index the pages of your website. In Laravel, you can automatically generate a sitemap to ensure your website stays up-to-date with the latest content and URLs. In this tutorial, we'll guide you through the process of automatically generating a sitemap in Laravel. Let's get started!

Step 1: Install the Laravel Sitemap Package 
To simplify the process of generating a sitemap in Laravel, we'll use a popular package called "laravel/sitemap". Open your terminal and navigate to your Laravel project directory. Run the following command to install the package:

composer require spatie/laravel-sitemap

Step 2: Configure the Sitemap 
After installing the package, you need to configure it in your Laravel application. Open the config/app.php file and add the following line to the providers array:

Spatie\Sitemap\SitemapServiceProvider::class,

Step 3: Generate the Sitemap Route 
Next, you need to define a route that will handle the sitemap generation. Open the routes/web.php file and add the following route definition:

Route::get('/sitemap', function () {
    return SitemapGenerator::create()
        ->add(Url::create('/')
            ->setPriority(1.0)
            ->setChangeFrequency(Url::CHANGE_FREQUENCY_DAILY))
        ->add(Url::create('/about')
            ->setPriority(0.8)
            ->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY))
        ->writeToFile(public_path('sitemap.xml'));
});

In this example, we define a /sitemap route that generates the sitemap. We specify the URLs to include in the sitemap, along with their priority and change frequency. Adjust the URLs and their properties based on your specific website structure and requirements.

Step 4: Generate the Sitemap 
To generate the sitemap, run the following command in your terminal:

php artisan sitemap:generate

This command will execute the /sitemap route and generate the sitemap XML file in the public directory of your Laravel application.

Step 5: Access the Sitemap 
Once the sitemap is generated, you can access it by visiting the /sitemap.xml URL of your Laravel application. For example, http://yourdomain.com/sitemap.xml.

Step 6: Automate the Sitemap Generation 
To automatically generate the sitemap at regular intervals, you can set up a cron job or schedule a task in Laravel. Open the app/Console/Kernel.php file and add the following code to the schedule method:

protected function schedule(Schedule $schedule)
{
    $schedule->command('sitemap:generate')->daily();
}

This example schedules the sitemap:generate command to run daily. Adjust the frequency according to your needs.