How to make a sitemap.xml with Laravel

Categorized as Laravel

Let’s try to make a simple sitemap.xml for you Laravel application. You could also use the Spatie’s Laravel sitemap package, but it could be an overkill if you need just a simple sitemap for your website.

First, we star with creating a Controller:

php artisan make:controller SitemapXmlController

In the controller we write this code (assuming you have categories, posts and some static pages). We query only the urls of these pages (slugs) from the database/

// App/Http/Controllers/SitemapXmlController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Platform;
use App\Models\Media;

class SitemapXmlController extends Controller
{
    public function index() {

        $categories = Category::all('slug');
        $posts = Post::all('slug');
        $statics = array('contact', 'careers', 'about');

        return response()->view('xml.index', [
            'categories' => $categories,
            'posts' => $posts,
            'statics' => $statics

        ])->header('Content-Type', 'text/xml');
      }

}

Next, we make a route:

...
use App\Http\Controllers\SitemapXmlController;
...

Route::get('/sitemap.xml', [SitemapXmlController::class, 'index']);

Finally, we make an index.blade.php, placing it into the /views/xml/ folder:

<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

    @foreach ($categories as $category)
        <url>
            <loc>{{ env('APP_URL') }}/{{ $category->slug }}</loc>
            <lastmod>{{ date('c') }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.8</priority>
        </url>
    @endforeach

    @foreach ($posts as $post)
        <url>
            <loc>{{ env('APP_URL') }}/posts/{{ $post->slug }}</loc>
            <lastmod>{{ date('c') }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.8</priority>
        </url>
    @endforeach

    @foreach ($statics as $static)
        <url>
            <loc>{{ env('APP_URL') }}/{{ $static }}</loc>
            <lastmod>{{ date('c') }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.8</priority>
        </url>
    @endforeach


</urlset>

It’s done, we have the sitemap xml file, you can test it out in your local or production environment:

Also, it is worth mentioning that using {{ url('/') }} instead of {{ env('APP_URL') }} in your blade file can cause your sitemap file use http but not https in the generated urls.

Second note is on the <lastmod> tag specification. We use the same current date in this tag for simplicity. You can add an actual date, such as created_at or updated_at, but Google search engine is not paying too much attention to that.

Leave a reply

Your email address will not be published.