Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

How to Generate XML Sitemap Without Using Package

Published on March 1, 2020 58 sec read

In this article, I’m going to share how to create an XML sitemap manually. Let’s assume that we have a model named Article for table articles. We’re going to generate sitemap for the articles table. Let’s get started:

Table of Contents

  1. Create a Controller
  2. Create a View
  3. Make Route & Test

Create a Controller

I’m creating a controller called SitemapController. Run this command to create the controller:

php artisan make:controller SitemapController

After creating the controller, open it and paste the below code:

SitemapController.php
<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class SitemapController extends Controller
{
    public function articles()
    {
        $articles = Article::all();

        return response()->view('sitemap-articles', compact('articles'))->header('Content-Type', 'text/xml');
    }
}

Create a View

Go to resources>views folder and make a view file named sitemap-articles.blade.php. Then open the file & paste this code:

articles.blade.php
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach ($articles as $article)
        <url>
            <loc> {{ url('') . '/' . $article->slug }}</loc>
            <lastmod>{{ $article->created_at->tz('UTC')->toAtomString() }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.5</priority>
        </url>
    @endforeach
</urlset>

Make Route & Test

Open web.php from the routes folder and make a route like:

web.php
Route::get('/sitemap-articles.xml', '[email protected]');

Now run the project and visit http://example.com/sitemap-articles.xml. You’ll see the output like:

That’s all. Thanks for reading. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *