Building a Sitemap in Your Laravel App with the Spatie Sitemap Package - TechvBlogs

Building a Sitemap in Your Laravel App with the Spatie Sitemap Package

Maximize your Laravel app's SEO impact with Spatie Sitemap. Learn to create efficient sitemaps for optimal crawlability, boosting search engine visibility and reach.

Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya

2 months ago

TechvBlogs - Google News

In the realm of Search Engine Optimization (SEO), ensuring optimal crawlability is paramount. To facilitate efficient website indexing, Google recommends incorporating a sitemap. This comprehensive document provides details about various pages, videos, and files on your website, aiding search engine bots in understanding their relationships. This article guides you through the process of building a sitemap in a Laravel application using the Spatie Sitemap package, which offers both automated and manual methods for sitemap creation.

Building a Sitemap in Your Laravel App with the Spatie Sitemap Package

Step 1: Install Laravel Application and Set Up Database

composer create-project --prefer-dist laravel/laravel laravel-sitemap
cd laravel-sitemap

Create a database in PHPMyAdmin, update the .env file with database details, and run migrations:

php artisan migrate

Step 2: Install Spatie Sitemap Package

composer require spatie/laravel-sitemap
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=sitemap-config

Modify the config/sitemap.php file according to your needs.

Step 3: Laravel Sitemap Auto Crawling

For automated crawling, install the package and specify the starting URL:

use Spatie\Sitemap\SitemapGenerator;

$path = public_path('sitemap.xml');

The generator can execute JavaScript on each page, ensuring that links injected into the DOM by JavaScript will also be crawled.

Step 4: Laravel Sitemap Manual Set Up

Implement the Sitemapable interface in your models:

use Spatie\Sitemap\Contracts\Sitemapable;
use Spatie\Sitemap\Tags\Url;

class Article extends Model implements Sitemapable
    public function toSitemapTag(): Url | string | array
        return Url::create(route('article.details', $this))

Generate the sitemap:

use Spatie\Sitemap\Sitemap;


Step 5: Usage in Laravel

Here's an example of how to use manual setup for generating a sitemap in a Laravel application:

    // Add indexes for different models
    ->add($this->build_index(Article::active()->get(), 'sitemap_articles.xml'))
    ->add($this->build_index(Partner::active()->get(), 'sitemap_partners.xml'))
    // Add individual URLs with priority and change frequency
    // Add more URLs as needed


By following these steps, you can efficiently build and configure a sitemap for your Laravel application, improving search engine crawlability and enhancing your website's SEO. For more detailed information, refer to the official Spatie Sitemap package documentation.


Comments (0)


Note: All Input Fields are required.