Create Sitemal XML file on the fly using Laravel

XML Sitemap Create Sitemal XML file on the fly using Laravel

In this article, we'll explore how to dynamically generate a sitemap.xml file within your Laravel application. This crucial SEO tool helps search engines efficiently crawl and index your website, improving your search visibility. We'll cover the essential steps and provide a practical example to get you started.

Route web.php

Create a simple route with sitemap processing in the controller itself

...
Route::get('sitemaps/articles.xml', [SitemapController::class, 'articles']);
...

SitemapController.php

Get all articles, create an array with simple classes for each article. Send the array to the sitemap template. Return template with header for XML file.

<?php

namespace App\Http\Controllers;

use App\Models\Article;

class SitemapController extends Controller
{
    /**
     * @return \Illuminate\Http\Response
     */
    public function articles()
    {
        //
        $items = [];

        //
        $articles = Article::query()
            ->orderBy('created_at', 'desc')
            ->get();

        foreach ($articles as $article) {
            $item = new \stdClass();
            $item->loc = route('article.view', $article->slug);
            $item->changefreq = 'weekly';
            $item->priority = '0.9';
            $items[] = $item;
        }

        $xml = view('sitemaps.articles', compact('items'));

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

sitemaps/articles.blade.php

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach($items as $item)
        <url>
            <loc>{{ $item->loc }}</loc>
            <changefreq>{{ $item->changefreq }}</changefreq>
            <priority>{{ $item->priority }}</priority>
        </url>
    @endforeach
</urlset>