Ads

How to Automatically Generate Sitemap with Laravel?

I use the spatie sitemap generator for all my laravel projects. And here is the steps I made written in brief.

I install the package via composer

  • composer require spatie/laravel-sitemap

I publish the config(uration) file by this command, in case I wanted to edit it.

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

this command will copy the config to config/sitemap.php where you would be able to change it depending on your project needs.

If I want to use it now, I create a code like this.

    SitemapGenerator::create('https://example.com')->writeToFile(public/sitemap.xml);
    

    I use this code inside one of controller I have - where it suits. But usually I don't use it inside controllers, I automate the sitemap creation.

    First, I generate a laravel command by this artisan command.

    php artisan make:command GenerateSitemap

    then I go to app/Console/Commands/GenerateSitemap.php in my project, and make it like this code.

    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Spatie\Sitemap\SitemapGenerator;
    
    class GenerateSitemap extends Command
    {
        /**
         * The console command name.
         *
         * @var string
         */
        protected $signature = 'sitemap:generate';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'Generate the sitemap.';
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            // modify this to your own needs
            SitemapGenerator::create(config('app.url'))
                ->writeToFile(public_path('sitemap.xml'));
        }
    }

    then I can generate the sitemap manually by this artisan command.

    php artisan sitemap:generate

    But I want to automate it, not convert code into command !!

    So I schedule sitemap generation daily by laravel scheduler. I just add the scheduling code to this file in my project app/Console/Kernel.php .

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

    note: just add the yellow-highlighted line of code to the schedule method. If there are more code on it, keep them too.

    Now, after a day, you'll see a sitemap created on your website. Just open this url (https://learns7.com/sitemap.xml). use your domain instead of learns7.com domain.

    If you want more information about spatie sitemap generator, or how to config it, read more on the official github repo here : https://github.com/spatie/laravel-sitemap/blob/master/README.md 

    If you want to get new posts, make sure to subscribe to Value In Brief by Email.