Laravel / PHP PHP Free

Laravel: Generate a Dynamic Sitemap.xml

Generate a sitemap.xml from your database in Laravel — always up to date, no file to maintain by hand.

27 lines · Updated Nov 26, 2026

Preview of Laravel: Generate a Dynamic Sitemap.xml
laravel-dynamic-sitemap.php
<?php

// routes/web.php
use App\Models\Post;
use Illuminate\Support\Facades\Route;

Route::get('/sitemap.xml', function () {
    $posts = Post::where('status', 'published')
        ->latest('updated_at')
        ->get(['slug', 'updated_at']);

    $xml = view('sitemap', compact('posts'))->render();

    return response($xml, 200)
        ->header('Content-Type', 'application/xml');
});

// resources/views/sitemap.blade.php
// <?xml version="1.0" encoding="UTF-8"?>
// <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
// @foreach ($posts as $post)
//   <url>
//     <loc>{{ url('/blog/' . $post->slug) }}</loc>
//     <lastmod>{{ $post->updated_at->toDateString() }}</lastmod>
//   </url>
// @endforeach
// </urlset>

About this snippet

A sitemap tells Google and Bing which pages exist on your site and when they last changed, which helps new content get discovered and indexed faster. A static sitemap.xml goes out of date the moment you publish a new post. This snippet generates the sitemap dynamically from your database, so every new post, product or page appears automatically.

How it works

  1. A route responds to /sitemap.xml.
  2. The controller loads published records — posts, pages, products — selecting only the columns it needs.
  3. It builds XML entries with each URL and its last-modified date and returns the response with an XML content type.

How to use it

  1. Add the route and code, then open /sitemap.xml in your browser to check the output.
  2. Add Sitemap: https://yoursite.com/sitemap.xml to your robots.txt.
  3. Submit the sitemap in Google Search Console and Bing Webmaster Tools.

Best practices

  • Include only canonical, indexable, published URLs — no drafts, admin pages, filters or duplicates.
  • Cache the generated XML for an hour or so, and clear it when content is published.
  • A single sitemap can hold up to 50,000 URLs; beyond that, use a sitemap index.

Common problems

  • "Couldn't fetch" in Search Console: make sure the response has an XML content type and nothing (like a blank line or debug bar) is printed before the XML declaration.
  • Invalid characters: escape URLs with special characters such as &.

FAQ

Do I need priority and changefreq tags? Google ignores them; an accurate lastmod is what matters.

Related: Deploy Laravel on a VPS · Log 404 errors

How to install

Add the route to routes/web.php and save the Blade view as resources/views/sitemap.blade.php. Change the model and URL to match your content. Cache the response for an hour on large sites.

Share this snippet

See all
Chat with us