Create a sitemap for laravel like rankmath

94 Views Asked by At

I want to create a sitemap for laravel, structure same like wordpress's rankmath sitemap...

i am adding a route like this

 - **Try 1**

    Route::get("/(*).xml", "SomeController@serve");

 - **Try 2**

    Route::get('{slug}.xml', 'SomeController@serve');

But it's not working... Can anyone provide better solution?

Rankmath sitemap

enter image description here

2

There are 2 best solutions below

3
Urvin Sanghavi On

Here's an example of how you can create a sitemap route with a parameter in Laravel:

Route::get('/{sitemap}.xml', 'SomeController@serve')->where('sitemap', '.*');

SomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SomeController extends Controller
{
    public function serve($sitemap)
    {
        $posts = []; // Replace this with your actual data retrieval logic

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

<!-- resources/views/sitemap.blade.php -->

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

Reference URL: https://chriswray.dev/posts/how-to-create-a-sitemap-in-laravel-for-a-website-that-contains-thousands-of-records

0
Denis Sinyukov On

I propose a different approach

  1. The sitemap files will be stored in public/ so that every time you don't have to create them on the fly.
  2. update the files when an entry is added or changed, using listener or observer.
Artisan::call('make:sitemap');
  1. Creation will be done in console command
  2. Don't forget to add sitemap to robots.txt file
class SitemapGenerate extends Command
{
    protected $signature = 'make:sitemap';

    public function handle(): void
    {
        $sitemapIndex = SitemapIndex::create();

        $entries = [
            $this->posts(),
        ];

        app(Pipeline::class)
            ->send($sitemapIndex)
            ->through($entries)
            ->then(function ($sitemapIndex) {
                /** @var Sitemap $sitemap */
                foreach ($this->sitemaps as $sitemapName => $sitemap) {
                    $sitemap->writeToFile(
                        public_path($sitemapName)
                    );
                }

                $sitemapIndex->writeToFile(
                    public_path('sitemap_index.xml')
                );

                $this->info('Sitemaps have been generated and saved.');

                $sitemapIndexUrl = route('home') . '/sitemap_index.xml';
            });
    }
    /**
     * @return \Closure
     */

    /**
     * @return \Closure
     */
    protected function pages(): \Closure
    {
        return function ($sitemapIndex, $next) {

            $sitemap = Sitemap::create();

            // Add homepage
            $sitemap->add(
                Url::create(route('home'))
                    ->setLastModificationDate(Carbon::now())
                    ->setChangeFrequency(Url::CHANGE_FREQUENCY_WEEKLY)
                    ->setPriority(1)
            );

            $posts = DB::table('posts')
                ->get(['slug', 'updated_at']);

            foreach ($posts as $post) {
                $sitemap->add(
                    Url::create(route('posts.show', $post->slug))
                        ->setLastModificationDate(Carbon::parse($post->updated_at))
                        ->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY)
                        ->setPriority(0.7)
                );
            }

            $sitemapName = 'posts_sitemap.xml';

            $this->sitemaps[$sitemapName] = $sitemap;

            /** @var SitemapIndex $sitemapIndex */
            $sitemapIndex->add(
                \Spatie\Sitemap\Tags\Sitemap::create($sitemapName)->setLastModificationDate(Carbon::now())
            );

            return $next($sitemapIndex);
        };
    }
}

Library for creating sitemap sitemap