How to Generate a Sitemap in Laravel: A Complete Guide
Search engines like Google and Bing use sitemaps to discover and index your website's pages efficiently. If you're building a Laravel application, generating a sitemap is straightforward with the help of a popular package.
In this guide, you'll learn how to generate a sitemap in Laravel using the Spatie Sitemap package.
What is a Sitemap?
A sitemap is an XML file that contains a list of URLs on your website. It helps search engines:
- Discover new pages
- Understand your site's structure
- Index content faster
- Improve SEO performance
A typical sitemap URL looks like:
https://yourwebsite.com/sitemap.xml
Prerequisites
Before starting, make sure you have:
- Laravel 10, 11,12 or newer installed
- Composer installed
- A running Laravel application
Step 1: Install the Sitemap Package
We'll use the excellent package provided by Spatie.
Run the following command:
composer require spatie/laravel-sitemap
Step 2: Create a Controller for Sitemap Generation
php artisan make:controller GenerateSitemap
Step 3: Open the controller and add the following code.
<?php
namespace App\Http\Controllers;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
use App\Models\Post;
class GenerateSitemap extends Controller
{
public function index(){
$sitemap = Sitemap::create();
/*
--------------------------------------------------------------------------
Static Pages
--------------------------------------------------------------------------
*/
$sitemap->add(
Url::create('/')
->setPriority(1.0)
->setChangeFrequency(Url::CHANGE_FREQUENCY_DAILY)
);
/*
--------------------------------------------------------------------------
Posts
--------------------------------------------------------------------------
*/
Post::with('category')
->where('status', 1)
->latest()->get()
->each(function ($post) use ($sitemap) {
$sitemap->add(
Url::create($post?->category->slug .'/'. $post->slug)
->setLastModificationDate($post->updated_at)
->setPriority(0.9)
->setChangeFrequency(Url::CHANGE_FREQUENCY_WEEKLY)
);
});
/*
|--------------------------------------------------------------------------
| Write File
|--------------------------------------------------------------------------
*/
$sitemap->writeToFile(public_path('sitemap.xml'));
return back()->with('success', 'Sitemap Generated Successfully!');
}
}
Step 4: Create a route to generate the sitemap.
use Illuminate\Support\Facades\Route;
Route::get('generate-sitemap', [GenerateSitemap::class, 'index']);
Step 5: Run command
php artisan serve
Step 6: Visit the sitemap URL to generate the sitemap.
http://127.0.0.1:8000/generate-sitemap
After visiting the sitemap generation URL, the sitemap file will be generated and saved in the public folder.
D:\laravel\mindwarezone\public\sitemap.xml