Make Sitemap Using Laravel

A website sitemap is a file that lists all the pages of your website, providing information about their structure and content. There are two main types:

XML Sitemap: For search engines to help them crawl and index your site better.

HTML Sitemap: For users to help them navigate your site easily.

Step 1: Define a Route

Route::get('sitemap.xml', 'SitemapController@index');

Step 2: Make a Controller

Make a controller  SitemapController.php

namespace App\Http\Controllers;

use App\Service\Front\SitemapService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Response;


class SitemapController extends Controller
{
    public function index()
    {
        $urls = Cache::remember(currentTheme() . 'site_map_cache', now()->addDays(7), static function () {
            return (new SitemapService())->generateSiteMapTemp();
        });

        $content = view(currentTheme() . 'sitemap', compact('urls'))->render();
        return Response::make($content, 200)->header('Content-Type', 'application/xml');
    }
}

Step 3:  Define a Service

This service will be called from controller along with cache feature. We have initially setup cache for 7 days

namespace App\Service\Front;

use App\Helper\Status;
use App\Models\Post\Post;

class SitemapService
{
    public function generateSiteMapTemp(): array
    {
        $siteMapUrls = [
            ['url' => route('home'), 'changefreq' => 'daily'],
            ['url' => url('/category'), 'changefreq' => 'daily'],
            ['url' => route('page', 'privacy-policy'), 'changefreq' => 'monthly'],
            ['url' => route('page', 'terms-and-conditions'), 'changefreq' => 'monthly'],
        ];

        

        //post url
        $posts = Post::select('slug')->where('status', Status::STATUS_PUBLISHED)->get();
        foreach ($posts as $post) {
            $siteMapUrls[] = [
                'url' => route('view-post', ['slug' => $post->slug]),
                'changefreq' => 'daily'
            ];
        }

        return $siteMapUrls;
    }

}

Step 4:  Making Blade File for sitemap.xml 

//sitemap.blade.php
Add below content in your sitemap.blade.php file

    @foreach ($urls as $url)
        
            {{ $url['url'] }}
            {{ \Carbon\Carbon::now()->toAtomString() }}
            {{ $url['changefreq'] }}
        
    @endforeach

Step 5:  Access sitemap.xml in Browser

http://127.0.0.1:8000/sitemap.xml

Tags: