Laravel 12 with Spatie Laravel-Sitemap: A Complete SEO Guide

Author

Kritim Yantra

Apr 16, 2025

Laravel 12 with Spatie Laravel-Sitemap: A Complete SEO Guide

In this comprehensive guide, we'll explore how to use Spatie's Laravel-Sitemap package in Laravel 12 to generate XML sitemaps that boost your website's SEO performance and search engine visibility.


Table of Contents

  1. Why Sitemaps Matter for SEO
  2. Installation & Setup
  3. Creating Your First Sitemap
  4. Adding Dynamic URLs
  5. Prioritizing Content
  6. Multi-Sitemap Strategy
  7. Image & Video Sitemaps
  8. Sitemap Index Files
  9. Automating Sitemap Generation
  10. Advanced SEO Techniques
  11. Testing & Validation
  12. Conclusion

1. Why Sitemaps Matter for SEO

Sitemaps help search engines:

  • Discover new pages faster
  • Understand site structure
  • Index priority content first
  • Identify update frequency
  • Index media content (images/videos)

Google reports that websites with sitemaps get indexed 50% faster on average.


2. Installation & Setup

Step 1: Install Laravel 12

composer create-project laravel/laravel seo-project
cd seo-project

Step 2: Install the Package

composer require spatie/laravel-sitemap

Step 3: Publish Config (Optional)

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

3. Creating Your First Sitemap

Basic Static Sitemap

Create a route in routes/web.php:

use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

Route::get('/sitemap', function () {
    return Sitemap::create()
        ->add(Url::create('/'))
        ->add(Url::create('/about'))
        ->add(Url::create('/contact'))
        ->writeToFile(public_path('sitemap.xml'));
});

Generating the File

Visit /sitemap to generate:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://example.com/</loc>
        <lastmod>2024-03-20T00:00:00+00:00</lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <!-- More URLs -->
</urlset>

4. Adding Dynamic URLs

From Database Models

use App\Models\Post;

Sitemap::create()
    ->add(Post::all()->map(function (Post $post) {
        return Url::create("/posts/{$post->slug}")
            ->setLastModificationDate($post->updated_at);
    }));

From Routes

collect(Route::getRoutes()->getRoutesByName())
    ->filter(fn ($route) => str_starts_with($route->getName(), 'public.'))
    ->each(fn ($route) => Sitemap::add(Url::create($route->uri())));

5. Prioritizing Content

Setting Priority & Change Frequency

Url::create('/pricing')
    ->setPriority(1.0)
    ->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY);

Recommended Values

Page Type Priority Frequency
Homepage 1.0 Daily
Product Pages 0.9 Weekly
Blog Posts 0.8 Monthly
Archive Pages 0.4 Yearly

6. Multi-Sitemap Strategy

Creating Specialized Sitemaps

// In app/Console/Commands/GenerateSitemaps.php
Sitemap::create()
    ->add(Url::create('/products'))
    ->writeToFile(public_path('sitemap-products.xml'));

Sitemap::create()
    ->add(BlogPost::all())
    ->writeToFile(public_path('sitemap-blog.xml'));

7. Image & Video Sitemaps

Image Sitemap Example

Url::create('/gallery')
    ->addImage(
        Image::create('/images/photo1.jpg')
            ->setTitle('Summer Vacation')
            ->setLicense('https://creativecommons.org/licenses/by/4.0/')
    );

Video Sitemap Example

Url::create('/videos')
    ->addVideo(
        Video::create()
            ->setTitle('Product Demo')
            ->setDescription('5-minute overview')
            ->setContentLocation('/videos/demo.mp4')
    );

8. Sitemap Index Files

Creating an Index

SitemapIndex::create()
    ->add('/sitemap-products.xml')
    ->add('/sitemap-blog.xml')
    ->writeToFile(public_path('sitemap.xml'));

Resulting Index File

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <sitemap>
        <loc>https://example.com/sitemap-products.xml</loc>
    </sitemap>
    <sitemap>
        <loc>https://example.com/sitemap-blog.xml</loc>
    </sitemap>
</sitemapindex>

9. Automating Sitemap Generation

Scheduled Command

php artisan make:command GenerateSitemap

In app/Console/Commands/GenerateSitemap.php:

protected $signature = 'sitemap:generate';

public function handle()
{
    SitemapGenerator::create(config('app.url'))
        ->writeToFile(public_path('sitemap.xml'));
}

Schedule in app/Console/Kernel.php:

$schedule->command('sitemap:generate')->daily();

10. Advanced SEO Techniques

Hreflang for Multilingual Sites

Url::create('/')
    ->addAlternate('/fr', 'fr')
    ->addAlternate('/es', 'es');

Handling Large Sites

For sites with 50,000+ URLs:

  • Split into multiple sitemaps
  • Use sitemap_index approach
  • Consider Laravel Queues for generation

11. Testing & Validation

Validate Your Sitemap

# Using curl
curl https://example.com/sitemap.xml | xmllint --noout --schema sitemap.xsd -

Google Search Console

  1. Submit your sitemap
  2. Monitor coverage reports
  3. Fix indexing errors

12. Conclusion

By implementing Spatie's Laravel-Sitemap:
Improved search engine visibility
Faster indexing of new content
Better crawl efficiency
Media content discovery
Multi-language support

Pro Tip: Combine with Laravel SEO Packages for maximum impact.

Ready to boost your SEO? Implement your sitemap today! 🚀

LIVE MENTORSHIP ONLY 5 SPOTS

Laravel Mastery
Coaching Class Program

KritiMyantra

Transform from beginner to Laravel expert with our personalized Coaching Class starting June 11, 2025. Limited enrollment ensures focused attention.

Daily Sessions

1-hour personalized coaching

Real Projects

Build portfolio applications

Best Practices

Industry-standard techniques

Career Support

Interview prep & job guidance

Total Investment
$200
Duration
30 hours
1h/day

Enrollment Closes In

Days
Hours
Minutes
Seconds
Spots Available 5 of 10 remaining
Next cohort starts:
June 11, 2025

Join the Program

Complete your application to secure your spot

Application Submitted!

Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.

What happens next?

  • Confirmation email with program details
  • WhatsApp message from our team
  • Onboarding call to discuss your goals

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts