Generate and Read Sitemap XML File in Laravel 12

Generate and Read Sitemap XML File in Laravel 12

Sitemaps are one of the most critical components of SEO today because they allow search engines (Google, Bing, Yahoo, etc.) to better crawl your website and its pages. With Laravel 12, creating and reading (parsing) an XML Sitemap file is relatively easy to do, either manually or using well-maintained packages.

Laravel Development Services

Discover how easy it is to create and use XML Sitemaps for better SEO in Laravel 12!

What is an XML Sitemap?

Think of an XML Sitemap as a map of your website. Search engines like Google use sitemaps to find and understand your site better. It’s similar to a table of contents that helps search engines find and list all of the pages on your website. This makes it simpler for people to find your site when they search online.

Steps to Generate and Read Sitemap XML File in Laravel 12:

Step 1: Install Laravel 12

composer create-project laravel/laravel example-app

Step 2: Create Post Migration and Model

php artisan make:migration create_posts_table

database/migrations/create_posts_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
php artisan migrate
php artisan make:model Post

Then, update the following code to the Post model.

app/Models/Post.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'slug', 'body'
    ];
}

Step 3: Create Post Factory

php artisan make:factory PostFactory

Next, copy the code below and update the PostFactory.php file.

database/factories/PostFactory.php

<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use App\Models\Product;
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
 */
class ProductFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Product::class;
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition(): array
    {
        return [
            'name' => $this->faker->name,
            'slug' => Str::slug($this->faker->name),
            'detail' => $this->faker->text,
        ];
    }
}

Then simply run the tinker command and create dummy posts.

php artisan tinker

App\Models\Post::factory()->count(30)->create();

Step 4: Create Route

In this step, we will create one route sitemap.xml, so let’s add it.

routes/web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SitemapController;
Route::get('sitemap.xml', [SitemapController::class, 'index']);

Step 5: Create Controller

app/Http/Controllers/SitemapController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Http\Response;
class SitemapController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(): Response
    {
        $posts = Post::latest()->get();
        return response()->view('sitemap', [
            'posts' => $posts
        ])->header('Content-Type', 'text/xml');
    }
}

Step 6: Create View File

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/{{ $post->slug }}</loc>
            <lastmod>{{ $post->created_at->tz('UTC')->toAtomString() }}</lastmod>
            <changefreq>daily</changefreq>
            <priority>0.8</priority>
        </url>
    @endforeach
</urlset>

Run Laravel App:

php artisan serve

http://localhost:8000/sitemap.xml 

Conclusion:

Generating and reading a sitemap XML file in Laravel 12 is essential for building SEO-friendly applications. Whether you use a package like Spatie or build your own solution, a well-maintained sitemap ensures better search engine visibility and faster indexing of your content.

By automating sitemap generation and understanding how to read it programmatically, you gain full control over your website’s SEO structure.

Hire laravel Developer

FAQ

1. Where can I find the default XML Sitemap for my Laravel application?

Typically, an XML Sitemap can be found in the public folder and accessed at the URL address: https://yourdomain.com/sitemap.xml.

2. Is it possible to create more than one sitemap using Laravel 12?

If you manage a large website or have a significant amount of data in multiple website directories, then it’s possible to create multiple sitemap files and consolidate them into a single sitemap index so that visitors only see one entry point.

3. How frequently should I update my sitemap?

A website that frequently updates content should submit a sitemap every day, whereas websites with infrequent updates could submit once every week.

4. Will Google automatically recognize a new Sitemap the moment it is uploaded?

Not always. Manually submitting Sitemaps via Google Search Console will ensure quicker indexing by search engines than waiting for automatic recognition.

Previous Article

Optimizing React Native Performance

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨