How to Generate Sitemap XML File in Laravel 9?

Published On: 03/06/2022 | Category: Laravel Laravel 9

Hi Dev,

This article is focused on laravel 9 generate sitemap. I explained simply about laravel 9 generate sitemap custom. I explained simply step by step how to create dynamic xml sitemap in laravel 9. I’m going to show you about laravel 9 sitemap xml.

Basically Sitemap ideally is a file that ends with a .xml extension; it is a simple file that contains the important website pages and allows the webmaster to inform search engines what pages are available for crawling.

This sitemap file is not just limited to laravel no matter what technology you are using but make sure you must generate and add a sitemap xml file to inform search engines.

Let's start following example:

Step 1: Install Laravel

First of all we are going from scratch new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2 : Create Post Migration and Model

In this second step, we need to create a new post migration and model by following command:

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()
    {
        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()
    {
        Schema::dropIfExists('posts');
    }
};

Now run the migration following the below command:

php artisan migrate

Now, run below command to create Post model.

php artisan make:model Post

So, then update following code to 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

Then, we will create Post factory class and generate dummy records using tinker command. so let's run below command to create post factory.

php artisan make:factory PostFactory
database/factories/PostFactory.php
<?php
  
namespace Database\Factories;
  
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
use Illuminate\Support\Str;
  
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;
    /**
     * Define the model's default state.
     *
     * @return array

     */
    public function definition()
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'body' => $this->faker->paragraph()
        ];
    }
}

Then simply run tinker command and create dummy posts.

php artisan tinker
    
App\Models\Post::factory()->count(30)->create();
Step 4 : Create Routes routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SitemapController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('sitemap.xml', [SitemapController::class, 'index']);
Step 5 : Create New Controller

In this second step, we need to create a new SitemapController; in this file, we will add two method index() and store() for render view and store image logic.

Let's create SitemapController by following command:

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

In the last section, we need to require sitemap.blade.php for display all posts and put following code:

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:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/sitemap.xml
Output :

I hope it can help you...