How to Generate a Dynamic XML Sitemap in Laravel 10

Spread the love

Hello Guys,

In this tutorial, we will delve into the process of generating a dynamic XML sitemap in Laravel 10. We’ll provide a step-by-step demonstration of creating a sitemap that’s compatible with Laravel 10. Additionally, we’ll offer a concise overview of the Laravel 10 sitemap XML format.

A sitemap is a structured file that lists all the pages of a website in a hierarchical manner. Its primary purpose is to facilitate both user and search engine navigation, allowing a clear understanding of the website’s content organization.

To illustrate, we will create a ‘posts‘ table featuring fields such as title, slug, and body. We’ll also establish a post factory to generate sample posts. Finally, we will generate an XML file containing a comprehensive list of post URLs. Following these instructions will result in the creation of a sitemap file tailored for your website, which can be conveniently submitted to webmaster tools for search engine optimization.”

This revised text includes keywords related to sitemap generation in Laravel 10 and emphasizes the importance of a structured sitemap for SEO purposes.

Generate SITEMAP in laravel 10 example:

Install Laravel

While it’s not obligatory, feel free to continue and execute the following command if you haven’t yet established your Laravel application:

Also Read: How to Get All Routes in Laravel 10

composer create-project laravel/laravel example-app

Create A Post Migration and Model File

In this step, we will guide you through creating both the migration and model. To initiate the process, simply execute the following command to construct the ‘posts‘ table.

php artisan make:migration create_posts_table

Now, proceed to modify the code within the migration file as illustrated below.

<?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');
    }
};

To execute the recently created migration, utilize the subsequent command:

Also Read: How to use Multiple Database Connections in LARAVEL 10

php artisan migrate

To build the Post model, employ the following command:

php artisan make:model Post

Transform the following code into a model-specific post.

<?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'
    ];
}

Create a Post Factory File

In this phase, we will create a Post factory class and utilize the Tinker command to generate dummy records. Follow the steps below to build a post factory by executing the command.

php artisan make:factory PostFactory

Update the PostFactory.php file by replicating the code provided below.

Also Read: How to Get the Last Inserted Id in Laravel 10?

<?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,
        ];
    }
}

Execute the Tinker command and generate placeholder posts.

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

Create a Route File

One route sitemap.xml will be created in this phase. Let’s add it, then.

Also Read: How to Get Database Name using Laravel?

<?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']);

Create a Controller File

create a SitemapController, follow these steps. In this process, we’ll create a new controller called “SitemapController” and implement the “index()” method. This function will gather all your posts and pass them to a blade file. The end result will be the generation of an XML file as the response. Below, we’ll guide you through the necessary code modifications for this purpose.

<?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');
    }
}

Create a View File

Let’s construct sitemap.blade.php as the final stage to display all content and add the following code:

<?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 Your Laravel App

After completing all necessary steps, you must now execute the command shown below and press Enter to launch the Laravel application:

php artisan serve

Now, Enter the provided URL into your web browser to view the app’s output.

Also Read: How To Generate Invoice PDF In Laravel 10

http://localhost:8000/sitemap.xml

Dive into our collection of Laravel blogs – your go-to source for expert insights.

Leave a Comment