How to Generate Dynamic Sitemap in Laravel?
Hey Guys,
In this tute, we will discuss how to create dynamic sitemap in laravel. Here you will learn how to create dynamic xml sitemap in laravel. you can see how to generate sitemap in laravel. This tutorial will give you a simple example of laravel create sitemap dynamic automatically. Let's see below example laravel generate sitemap.xml.
A sitemap is a file that contains a list of all the pages on a website, organized in a hierarchical structure. It is intended to help search engines and users navigate and understand the structure of a website's content.
In this example, we will create a posts table with a title, slug, and body. Then, we will create a factory for generating dummy posts. Finally, we will generate an XML file and list all the URLs for the posts. This is a very basic example, so let's follow along, and you will have a sitemap file for your website that you can submit to the webmaster's tool.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.
Let's follow below steps:
Step 1: Install Laravel
This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Create Post Migration and Model
In this step, we will create migration and model. So let's run below command to create posts table.
php artisan make:migration create_posts_table
Next, simple update below code to migration file.
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');
}
};
Then run created new migration with below command:
php artisan migrate
Now, run below command to create Post model.
php artisan make:model Post
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
In this step, 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
Next, copy below code and update 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 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;
/*
|--------------------------------------------------------------------------
| 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
In this step, we have to create new controller as SitemapController with index(). we will get all posts and pass to blade file. we will return response as xml file. so let's update follow code:
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
In Last step, let's create 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 the required steps have been done, now you have to type the given below 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Request Method in Laravel?
- How to Add Google Map in Laravel?
- Laravel Group By with Max Value Query Example
- Laravel Firebase Push Notification to Android and IOS App Example
- How to Get Current Week Records in Laravel?
- How to Create Dynamic Navigation Bar in Laravel?
- Laravel Sweet Alert Confirm Delete Example
- How to Get Current User Location in Laravel?
- Laravel Inertia JS Pagination Example
- Laravel Razorpay Payment Gateway Example
- Laravel Send Mail using Mailgun Example
- Laravel Eloquent Where Query Examples
- How to Get Query Log in Laravel Eloquent?
- Laravel Create JSON File & Download From Text Example