Create Sitemap in a Laravel Application
A sitemap is an xml file that lists all the URLs within a domain.
Sitemaps are important for SEO of a website. Sitemaps helps search engines to find pages for indexing.
In this tutorial, we will generate a sitemap for a Laravel React web application using spatie/laravel-sitemap .
Install spatie/laravel-sitemap
composer require spatie/laravel-sitemap
Publish the Configuration
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=config
This will copy the default config to config/sitemap.php that you can edit.
Create GenerateSitemap.php
Create a GenerateSitemap.php file inside yourproject/app/Console/Commands/ directory of your project and add the sitemap generating code.
Here is an example of generating a sitemap with having to add urls to it manually:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;
class GenerateSitemap extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate the sitemap';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command sudo php artisan sitemap:generate.
*
* @return mixed
*/
public function handle()
{
SitemapGenerator::create('https://www.yourdomain.com')
->getSitemap()
->add(Url::create('/page1')->setPriority(0.8))
->add(Url::create('/page2')->setPriority(0.8))
->add(Url::create('/page3')->setPriority(0.8))
->add(Url::create('/page4')->setPriority(0.8))
//here we have added four links, but you can add as many as you'd like
//location where you want to generate your sitemap file
->writeToFile('/home/yourdir/public_html/sitemap.xml');
return 'Sitemap generated';
}
}
Generate sitemap.xml File
Open terminal, nagivate inside your project folder and execute the command below:
php artisan sitemap:generate
This will generate a sitemap.xml file in the location that you have specified in GenerateSitemap.php file.