How to add a sitemap to a Laravel application?
Install the spatie/laravel-sitemap package: Install and introduce the spatie/laravel-sitemap package through Composer to support sitemap generation function; 2. Optional configuration: Publish configuration files to customize cache, tags or style settings; 3. Create routes to generate sitemap: Create routes in web.php using SitemapGenerator and return sitemap.xml; 4. Recommended use of planning tasks: Create Artisan commands and generate sitemap regularly daily through Laravel scheduler to improve performance; 5. Service static files: The route only returns the generated static sitemap.xml files to avoid duplicate generation; 6. Add dynamic URLs: Manually add dynamic content such as blog posts through Sitemap::create() and set update frequency, priority and other attributes; 7. Submit to search engines: Submit the generated sitemap.xml to Google Search Console and Bing Webmaster Tools to complete SEO optimization, ultimately implementing efficient and maintainable sitemap integration for Laravel applications.
Adding a sitemap to a Laravel application is a straightforward process, especially if you're using a package like spatie/laravel-sitemap
—which is the most popular and well-maintained solution. Here's how to do it step by step.

1. Install the Spatie Sitemap Package
First, install the package via Composer:
composer requires spatie/laravel-sitemap
This package handles generating sitemaps, managing URLs, and even support sitemap indexes for large sites.

2. Publish and Configure (Optional)
You can publish the config file to customize behavior:
php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider"
This creates config/sitemap.php
. You usually don't need to change anything unless you want to customize cache settings, tags, or styling.

3. Generate the Sitemap
Create a route in routes/web.php
to generate and serve the sitemap:
use Spatie\Sitemap\SitemapGenerator; Route::get('/sitemap.xml', function () { // Generate the sitemap SitemapGenerator::create(config('app.url'))->writeToFile(public_path('sitemap.xml')); // Return the file return response()->file(public_path('sitemap.xml')); });
⚠️ Note : This regenerates the sitemap on every request. That's fine for small or infrequently changing sites, but not ideal for large or high-traffic ones.
4. Better Approach: Use a Scheduled Command (Recommended)
For production, generate the sitemap periodically using Laravel's task scheduler.
a. Create an Artisan Command
php artisan make:command GenerateSitemap
Edit the new command in app/Console/Commands/GenerateSitemap.php
:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Spatie\Sitemap\SitemapGenerator; class GenerateSitemap extends Command { protected $signature = 'sitemap:generate'; protected $description = 'Generate the sitemap'; public function handle() { SitemapGenerator::create(config('app.url')) -> writeToFile(public_path('sitemap.xml')); $this->info('Sitemap generated successfully.'); } }
b. Schedule the Command
In app/Console/Kernel.php
, add the command to the schedule:
protected function schedule(Schedule $schedule) { $schedule->command('sitemap:generate')->daily(); }
Now the sitemap will be regenerated once per day.
c. Serve the Static File
Update your route to just serve the static file without regenerating:
Route::get('/sitemap.xml', function () { return response()->file(public_path('sitemap.xml')); });
Make sure the file exists. You can manually run the command once to create it:
php artisan sitemap:generate
5. Add Dynamic URLs (Optional)
If you have dynamic content (eg, blog posts), you can manually add them:
use Spatie\Sitemap\Sitemap; use App\Models\Post; Sitemap::create() ->add('/home') ->add('/about') ->add('/contact') ->add( Post::where('published', true)->get() ->map(function (Post $post) { return $post->toSitemapTag(); }) ) -> writeToFile(public_path('sitemap.xml'));
Make sure your model (eg, Post
) implements Spatie\Sitemap\Tags\Url
or use ->add()
with Url::create()
:
use Spatie\Sitemap\Tags\Url; ->add(Url::create("/blog/{$post->slug}") ->setLastModificationDate($post->updated_at) ->setChangeFrequency('weekly') ->setPriority(0.8))
6. Submit to Search Engines
Once your sitemap.xml
is accessible (eg, https://yoursite.com/sitemap.xml
), submit it to:
- Google Search Console
- Bing Webmaster Tools
Summary
- ✅ Use
spatie/laravel-sitemap
for easy integration - ✅ Generate sitemap via a scheduled command in production
- ✅ Serve a static XML file for performance
- ✅ Include dynamic content by manually adding URLs
- ✅ Submit to search engines
That's it. Your Laravel app now has a working, SEO-friendly sitemap.
The above is the detailed content of How to add a sitemap to a Laravel application?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

LaravelSanctum is suitable for simple, lightweight API certifications such as SPA or mobile applications, while Passport is suitable for scenarios where full OAuth2 functionality is required. 1. Sanctum provides token-based authentication, suitable for first-party clients; 2. Passport supports complex processes such as authorization codes and client credentials, suitable for third-party developers to access; 3. Sanctum installation and configuration are simpler and maintenance costs are low; 4. Passport functions are comprehensive but configuration is complex, suitable for platforms that require fine permission control. When selecting, you should determine whether the OAuth2 feature is required based on the project requirements.

The most common way to generate a named route in Laravel is to use the route() helper function, which automatically matches the path based on the route name and handles parameter binding. 1. Pass the route name and parameters in the controller or view, such as route('user.profile',['id'=>1]); 2. When multiple parameters, you only need to pass the array, and the order does not affect the matching, such as route('user.post.show',['id'=>1,'postId'=>10]); 3. Links can be directly embedded in the Blade template, such as viewing information; 4. When optional parameters are not provided, they are not displayed, such as route('user.post',

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

The core of handling HTTP requests and responses in Laravel is to master the acquisition of request data, response return and file upload. 1. When receiving request data, you can inject the Request instance through type prompts and use input() or magic methods to obtain fields, and combine validate() or form request classes for verification; 2. Return response supports strings, views, JSON, responses with status codes and headers and redirect operations; 3. When processing file uploads, you need to use the file() method and store() to store files. Before uploading, you should verify the file type and size, and the storage path can be saved to the database.

There are two main methods for request verification in Laravel: controller verification and form request classes. 1. The validate() method in the controller is suitable for simple scenarios, directly passing in rules and automatically returning errors; 2. The FormRequest class is suitable for complex or reusable scenarios, creating classes through Artisan and defining rules in rules() to achieve code decoupling and reusing; 3. The error prompts can be customized through messages() to improve user experience; 4. Defining field alias through attributes() to make the error message more friendly; the two methods have their advantages and disadvantages, and the appropriate solution should be selected according to project needs.

The main difference between LaravelBreeze and Jetstream is positioning and functionality. 1. In terms of core positioning, Breeze is a lightweight certified scaffolding that is suitable for small projects or customized front-end needs; Jetstream provides a complete user system, including team management, personal information settings, API support and two-factor verification, which is suitable for medium and large applications. 2. In terms of front-end technology stack, Breeze uses Blade Tailwind by default, which prefers traditional server-side rendering; Jetstream supports Livewire or Inertia.js (combined with Vue/React), which is more suitable for modern SPA architectures. 3. In terms of installation and customization, Breeze is simpler and easier to use

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

Database Factory is a tool in Laravel for generating model fake data. It quickly creates the data required for testing or development by defining field rules. For example, after using phpartisanmake:factory to generate factory files, sets the generation logic of fields such as name and email in the definition() method, and creates records through User::factory()->create(); 1. Supports batch generation of data, such as User::factory(10)->create(); 2. Use make() to generate uninvented data arrays; 3. Allows temporary overwriting of field values; 4. Supports association relationships, such as automatic creation
