How to Generate XML Sitemap Without Using Package

avatar
Published: Mar 01, 2020 - Updated: Mar 16, 2022

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. ?

Comments

No comments yet…