Table of Contents
2. Publish and Configure (Optional)
3. Generate the Sitemap
4. Better Approach: Use a Scheduled Command (Recommended)
a. Create an Artisan Command
b. Schedule the Command
c. Serve the Static File
5. Add Dynamic URLs (Optional)
Summary
Home PHP Framework Laravel How to add a sitemap to a Laravel application?

How to add a sitemap to a Laravel application?

Jul 29, 2025 am 03:30 AM

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.

How to add a sitemap to a Laravel application?

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.

How to add a sitemap to a Laravel application?

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.

How to add a sitemap to a Laravel application?

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.

How to add a sitemap to a Laravel application?

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.


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 = &#39;sitemap:generate&#39;;
    protected $description = &#39;Generate the sitemap&#39;;

    public function handle()
    {
        SitemapGenerator::create(config(&#39;app.url&#39;))
            -> writeToFile(public_path(&#39;sitemap.xml&#39;));

        $this->info(&#39;Sitemap generated successfully.&#39;);
    }
}

b. Schedule the Command

In app/Console/Kernel.php , add the command to the schedule:

 protected function schedule(Schedule $schedule)
{
    $schedule->command(&#39;sitemap:generate&#39;)->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(&#39;/sitemap.xml&#39;, function () {
    return response()->file(public_path(&#39;sitemap.xml&#39;));
});

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(&#39;/home&#39;)
    ->add(&#39;/about&#39;)
    ->add(&#39;/contact&#39;)
    ->add(
        Post::where(&#39;published&#39;, true)->get()
            ->map(function (Post $post) {
                return $post->toSitemapTag();
            })
    )
    -> writeToFile(public_path(&#39;sitemap.xml&#39;));

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(&#39;weekly&#39;)
    ->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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
4 weeks ago By 百草
Tips for Writing PHP Comments
3 weeks ago By 百草
Commenting Out Code in PHP
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1509
276
Choosing between Laravel Sanctum and Passport for API authentication Choosing between Laravel Sanctum and Passport for API authentication Jul 14, 2025 am 02:35 AM

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.

Generating URLs for Named Routes in Laravel. Generating URLs for Named Routes in Laravel. Jul 16, 2025 am 02:50 AM

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',

What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

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.

Handling HTTP Requests and Responses in Laravel. Handling HTTP Requests and Responses in Laravel. Jul 16, 2025 am 03:21 AM

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.

How to perform Request Validation in Laravel? How to perform Request Validation in Laravel? Jul 16, 2025 am 03:03 AM

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.

Understanding the differences between Laravel Breeze and Jetstream. Understanding the differences between Laravel Breeze and Jetstream. Jul 15, 2025 am 12:43 AM

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

Explain Laravel Eloquent Scopes. Explain Laravel Eloquent Scopes. Jul 26, 2025 am 07:22 AM

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.

Generating and using database factories in Laravel. Generating and using database factories in Laravel. Jul 16, 2025 am 02:05 AM

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

See all articles