If your website is updating quite frequently like blogging websites and you want to get rid of the daily hassle of creating a sitemap and submit to Google, then you came to the right place. In this article, you will learn how to create dynamic sitemaps with all crawlable urls automatically.
I assume that you have already set up your laravel project, if not then follow these steps: How to install and create laravel project
The steps are very simple for generating a sitemap, follow them step by step. Let’s dive right into it.
Step 1
Install the package called “spatie/laravel-sitemap” using composer
composer require spatie/laravel-sitemap
Step 2
Update default configuration by publishing this package by following command
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider"
Step 3
Now we will automate the process of generating sitemap by creating custom laravel command
Following command will generate a new file in app/Console/Commands/GenerateSitemap.php
php artisan make:command GenerateSitemap
Step 4
Open GenerateSitemap.php file and edit the content as shown below:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Spatie\Sitemap\SitemapGenerator; class GenerateSitemap extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'generate:sitemap'; /** * The console command description. * * @var string */ protected $description = 'Generates a sitemap'; /** * Execute the console command. * * @return int */ public function handle() { // creates sitemap with all urls in your website SitemapGenerator::create("https://localhost.com") ->writeToFile(public_path('sitemap.xml')); } }
Step 5
Now we will run following command to create sitemap
php artisan generate:sitemap
After running the above command, you will find new sitemap.xml file in your app/public directory.
Step 6
If you want to remove the task of generating sitemap from your daily TODO list then automate the task using Laravel Task Scheduling
Add following command to your app/Console/Kernal.php file.
protected function schedule(Schedule $schedule) { // runs generate sitemap command in weekdays(Mon-Fri) at 9 am $schedule->command('generate:sitemap')->weekdays()->at('9:00'); // or run this command for daily routine $schedule->command('generate:sitemap')->daily(); }
Finally, we successfully set up the automatically generation of a sitemap. I hope this article is helpful to you. Thank you for reading.