Custom Sitemap Creation in Laravel

This guide explains how to create a custom sitemap in Laravel using SimpleXMLElement and DOMDocument. You will also learn about Laravel Facades, the XML attributes used, and the benefits of a dynamically generated sitemap.

Step-by-Step Guide

1. Define the Sitemap Creation Method

In your Laravel controller or service, create a method to generate the sitemap:

use SimpleXMLElement;
use DOMDocument;
use Illuminate\Support\Facades\Storage;

public function create()
{
    $xml = new SimpleXMLElement('');
    $xml->addAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
    $xml->addAttribute("xmlns:xhtml", "http://www.w3.org/1999/xhtml");

    $sitemap = $this->sitemap($xml);
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->loadXML($sitemap);
    $dom->encoding = 'UTF-8';
    $dom->formatOutput = true;

    Storage::disk('public_direct')->put('sitemap.xml', $dom->saveXML());
}

2. Define the Sitemap Structure

Define a method to structure the sitemap content:

public function sitemap($xml)
{
    $docker = Docker::select('slug', 'updated_at')->get();

    // Initialize arrays for URLs and their update timestamps
    $dockerUrl = $this->processUrls($docker, '/docker');

    // Process Static URLs
    foreach($this->staticUrl as $staticUrlObject) {
        $static[] = [
            'url' => config('app.url') . $staticUrlObject,
            'updated_at' => '2024-07-27T12:16:17+00:00' // Use current time for static URLs
        ];
    }

    // Merge all URLs and their update timestamps
    $sitemapUrl = array_merge($static, $dockerUrl);
    $sitemapUrl[] = [
        'url' => config('app.url'),
        'updated_at' => '2024-07-27T12:16:17+00:00' // Use current time for the base URL
    ];

    // Generate the sitemap
    foreach($sitemapUrl as $entry) {
        $sitemap = $xml->addChild('url');
        $sitemap->addChild('loc', $entry['url']);
        $sitemap->addChild('lastmod', $entry['updated_at']);
        $sitemap->addChild('changefreq', "daily");
        $sitemap->addChild('priority', "1.0");
    }

    $sitemap = $xml->asXML();

    return $sitemap;
}

Define a method to get all urls dynamically:


    function processUrls($items, $pathPrefix, $timestampFormat = 'Y-m-d\TH:i:sP') {
        $urls = [];
        foreach($items as $object) {
            $urls[] = [
                'url' => config('app.url') . $pathPrefix . '/' . $object->slug,
                'updated_at' => $object->updated_at->format($timestampFormat)
            ];
        }
        return $urls;
    }

Understanding the XML Attributes

Laravel Facades Explained

In the provided code, Storage::disk('public_direct') is a Laravel Facade. Facades provide a static-like interface to underlying classes in the service container. In this case, Storage is a facade for the file storage system, allowing you to interact with the filesystem in a more convenient and readable way. Facades help simplify common operations such as file storage, retrieval, and URL generation. For more information on using Laravel Facades, see the Laravel documentation on the Storage facade.

Benefits of Using a Custom Sitemap

By following these steps, you can create a custom, dynamic sitemap for your Laravel application that is both accessible and useful for search engine optimization.

Published By: Krishanu Jadiya
Updated at: 2024-08-03 16:25:27

Card Image

Latest JavaScript Features | ES2023 and Beyond

Explore the latest features of JavaScript including ES2023 updates such as Array.findLast(), top-level await, and more. Stay up-to-date with the newest advancements in JavaScript.

Card Image

Understanding JavaScript Hoisting with Examples

Learn about JavaScript hoisting, how it works, and see practical examples demonstrating variable and function hoisting.

Card Image

Dynamic Tabs to Dropdown on Mobile

Convert tabs to dropdown on mobile devices dynamically using JavaScript. Learn how to create a responsive tab system that adapts to different screen sizes.

Card Image

JavaScript Array Functions - Complete Guide

Learn about the most commonly used JavaScript array functions, including map, filter, reduce, forEach, and more. Enhance your coding skills with these essential methods.