Generate dynamic sitemaps in laravel

Here, let's see how to create a generated sitemap in Laravel. This article will explain the dynamic xml sitemap in laravel. I have explained here how to easily create a step by step laurel sitemap xml. Here you will learn how to generate a laravel sitemap dynamic as well as creating a basic example of a laravel generated sitemap file.

Search engines will need a sitemap to read our website which contains a list of your website's URLs. You can submit a Sitemap file to Webmaster Tools to notify search engines. So sitemap is very important for every website to put in search engine or even for SEO.

Here we can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

We will first install the Laravel app then we need the database, so we will create a article table with title, slug and description along with the database. Then we will build a factory for the dummy post. We will then generate an XML file and list all the URLs for the posts. That is a very basic example.

Let's go follow below steps:

Step 1 : Install Laravel

If you haven't created a laravel app, you need to run the following command

composer create-project laravel/laravel demo-app

Step 2 : Create Migration

In this step, we will create migration and model. So let us run the following command to create a post table.

php artisan make:migration create_posts_table

Now next, goto database/migrations/create_articles_table.php migration file. and edit bellow code.

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

Then run created new migration with below command:

php artisan migrate

Step 3 : Create Model

Now, run below command to create Post model.

php artisan make:model Post

Then goto app/Models/Post.php model file and update following code.

<?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 4 : Create Route

In this step, we will create a root sitemap.xml. Which is as follows

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 Controller

Now we have to create a new controller as a sitemap controller. We will get all the articles in it and send it to the blade file. And should return feedback as a psi xml file.

Goto 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 View File

In this last step, we create sitemap.blade.php to display all the posts accordingly.

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

Step 7: Run Laravel Applicatuion

Now you have to type the following command which will 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

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

http://localhost:8000/sitemap.xml

Output:

Generate dynamic sitemaps in a laravel

I hope it can help you...