Laravel 10 - How to Generate Sitemap
Laravel 10 - How to Generate Sitemap
In this tutorial, we will discuss how to generate a sitemap in Laravel 10. A sitemap improves SEO by helping search engines index your site efficiently.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide takes you through the process of generating an XML sitemap in a Laravel application using the Spatie Sitemap package. You'll begin by setting up a fresh Laravel project and installing frontend dependencies. After that, you'll integrate the sitemap package and publish its configuration to gain full control over how your sitemap behaves. You’ll then create simple static pages (like About and Contact), define their routes, and build a manual sitemap generator route. Finally, you’ll learn how to test your sitemap, extend it to include dynamic content (like blog posts), customize sitemap attributes such as change frequency and priority, and even set up automation for production using cron jobs. By the end, you’ll have a flexible and dynamic sitemap system ready for search engines.
Step # 1 : Set Up Your Laravel Project.
To get started, either create a new Laravel project or work with an existing one. If you have Laravel installed globally, you can spin up a new project using.
laravel new sitemap
Alternatively, if you prefer using Composer, run.
composer create-project laravel/laravel --prefer-dist sitemap
These commands will scaffold a fresh Laravel application with all the necessary dependencies and core files, like the .env file, routes, controllers, and more, giving you a clean foundation to begin development.
Step # 2 : Navigate to Your Project and Set Up Frontend Assets.
Open your terminal (like Git Bash) and head to the root directory of your Laravel project.
cd c:/xampp/htdocs/sitemap
Once inside the project folder, install the frontend dependencies and start the Vite development server.
npm install && npm run dev
Keep the Vite server running, and open a new terminal window or tab to run additional Laravel commands as needed, all from the same project directory.
Step # 3 : Add the Sitemap Package.
To easily generate sitemaps in your Laravel app, we’ll use the Spatie Laravel Sitemap package. This package simplifies the process by automatically crawling your site and creating a structured sitemap file. Run the following command in your project’s root directory to install it.
composer require spatie/laravel-sitemap
This will pull in the package and its dependencies, preparing your Laravel app to generate sitemaps effortlessly.
Step # 4 : Publish the Sitemap Configuration File.
Once the Spatie Sitemap package is installed, the next step is to publish its configuration file. This file allows you to fine-tune how the sitemap is generated according to your needs. By running the following Artisan command, you'll create a sitemap.php configuration file in the config directory of your project.
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=sitemap-config
This file will give you control over various settings, such as the location of the sitemap, caching behavior, and other options. With this configuration, you can tailor the sitemap generation process to suit your project's requirements, ensuring it fits perfectly into your application
Step # 5 : Create Sample Pages.
To test if our sitemap includes the right pages, we’ll create two simple views: one for the About page and another for Contact. These basic pages will give the sitemap generator something to crawl. Inside the resources/views directory, create two files named about.blade.php and contact.blade.php. Each file should contain a basic HTML structure with a heading and a short description, like the examples below.
about.blade.php
<!DOCTYPE html>
<html>
<head>
<title>About - Code Shortcut</title>
</head>
<body>
<h1>About Page</h1>
<p>Some description related to the about page.</p>
</body>
</html>
contact.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Contact - Code Shortcut</title>
</head>
<body>
<h1>Contact Page</h1>
<p>Some description related to the contact page.</p>
</body>
</html>
These views don’t need to be fancy, they’re just placeholders to help us confirm that our sitemap setup is working properly.
Step # 6 : Define Routes for Pages and Sitemap.
Now that we’ve created the About and Contact views, let’s set up the routes so these pages are accessible in the browser. We’ll also add a route to manually generate the sitemap and save it as an XML file. Open your routes/web.php file and add the following.
<?php
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
use Carbon\Carbon;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
Route::get('/', function(){
return view('welcome');
});
Route::get('/about', function(){
return view('about');
});
Route::get('/contact', function(){
return view('contact');
});
Route::get('/sitemap', function () {
//Lets generate sitemap manually
$sitemap = Sitemap::create()
->add(Url::create('/'))
->add(Url::create('/about'))
->add(Url::create('/contact'));
$sitemap->writeToFile(public_path('sitemap.xml'));
return "success";
});
This setup ensures your basic pages are viewable, and the /sitemap route gives you a quick way to manually generate a sitemap file in your public directory.
Step # 7 : Test Your Sitemap and Explore Dynamic Options.
With everything in place, it's time to run your Laravel app and test the sitemap functionality. Start the development server by running.
php artisan serve
Now open your browser and visit: http://127.0.0.1:8000/sitemap. You should see a simple success message, this confirms that the sitemap was generated and saved to your public directory.
To view the actual XML file, go to: http://127.0.0.1:8000/sitemap.xml. This will display the sitemap contents in your browser.
Adding Dynamic Pages to Your Sitemap
You’re not limited to static routes. You can include dynamic content like blog posts, tags, or categories by modifying the sitemap route. Here's an example that adds blog posts from the database.
use App\Models\Post;
Route::get('/sitemap', function () {
$sitemap = Sitemap::create()
->add(Url::create('/'))
->add(Url::create('/about'))
->add(Url::create('/contact'));
$posts = Post::all();
foreach ($posts as $post) {
$sitemap->add("/post/{$post->slug}");
}
$sitemap->writeToFile(public_path('sitemap.xml'));
return 'Sitemap generated successfully!';
});
Customizing Sitemap Entries
You can also fine-tune each URL by setting metadata such as the last modified date, change frequency, and priority.
use Carbon\Carbon;
Route::get('/sitemap', function () {
$sitemap = Sitemap::create()
->add(
Url::create('/')
->setLastModificationDate(Carbon::yesterday())
->setChangeFrequency(Url::CHANGE_FREQUENCY_YEARLY)
->setPriority(0.1)
);
$sitemap->writeToFile(public_path('sitemap.xml'));
return 'Custom sitemap created!';
});
Automating It for Production
For live applications, consider setting up a scheduled task (cron job) to regenerate the sitemap automatically at regular intervals, this ensures your sitemap always reflects the latest content on your site.
Conclusion
By following this guide, you’ve successfully set up a dynamic XML sitemap in your Laravel application. You now have a foundation that allows for both static and dynamic content, ensuring search engines can easily crawl and index your site. This setup can be further customized with additional features like metadata adjustments and automated sitemap generation for production. With this in place, your site is better optimized for search engines, giving it a solid boost in SEO.
For more details, be sure to check out the official Spatie documentation and Laravel’s sitemap resources.
For more details, be sure to check out the official Spatie documentation and Laravel’s sitemap resources.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments