Dynamically Generate XML Sitemap - Laravel

Date : 1st April 2026

Summary: Generates/updates the sitemap.xml file dynamically as webpages are opened.

When we want to create a sitemap.xml file, it would become very cumbersome to write down all URLs manually.

So this code generates/updates the sitemap.xml file dynamically as we visit the webpage.

So add this code and visit every page of your website once, and your sitemap.xml file will be generated.

After your file is generated, comment out this code so it does not affect the performance.

In case you have any changes in URLs, uncomment this code, visit the new pages/URLs of the website and delete the old URLs manually from the sitemap.xml file.

Add Middleware:

app/Http/Middleware/AppendToSitemap.php
app/Http/Kernel.php

Apply Middleware:

routes/web.php

Visit every page of the website:

Now, visit any webpage from your website and your sitemap.xml will be generated at public/sitemap.xml location.

Visit every page of your website that you want to be included in sitemap.xml file.

After it, comment "sitemap_builder" middleware from routes/web.php file

Concept:

In today's AI era, the importance of concepts is more significant than technical things. This blog tells about both the technical aspects and the concept of how sitemap.xml can be generated dynamically. This concept can be applied to any web technology, whether your website is built on PHP, Java, ASP.NET, or any other technology.

If you have any questions, feel free to ask.