Get Appointment

Blog Single

Creating a Sitemap for Your Laravel Website with Spatie Laravel Sitemap

  • Vfix Technology
  • 17 Dec 2023
  • 121 Views

Creating a sitemap for your Laravel website is an important step in improving your search engine optimization (SEO) and making it easier for search engines to crawl your website. The Spatie Laravel Sitemap package is an easy and efficient way to create a sitemap for your website. This package is available on GitHub at the following link: https://github.com/spatie/laravel-sitemap

Here is a step-by-step guide on how to use the Spatie Laravel Sitemap package to create a sitemap for your Laravel website:

1.Start by installing the package using Composer by running the following command:

composer require spatie/laravel-sitemap.

2. Next, add the Sitemap facade to your config/app.php file:

'aliases' => [
    // ...
    'Sitemap' => Spatie\Sitemap\SitemapFacade::class,
],

3. Publish the package's config file by running the command: 

php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag="config"

You can override the default options for the crawler. First publish the configuration:

This will copy the default config to config/sitemap.php where you can edit it.

<?php

use GuzzleHttp\RequestOptions;
use Spatie\Sitemap\Crawler\Profile;

return [

    /*
     * These options will be passed to GuzzleHttp\Client when it is created.
     * For in-depth information on all options see the Guzzle docs:
     *
     * http://docs.guzzlephp.org/en/stable/request-options.html
     */
    'guzzle_options' => [

        /*
         * Whether or not cookies are used in a request.
         */
        RequestOptions::COOKIES => true,

        /*
         * The number of seconds to wait while trying to connect to a server.
         * Use 0 to wait indefinitely.
         */
        RequestOptions::CONNECT_TIMEOUT => 10,

        /*
         * The timeout of the request in seconds. Use 0 to wait indefinitely.
         */
        RequestOptions::TIMEOUT => 10,

        /*
         * Describes the redirect behavior of a request.
         */
        RequestOptions::ALLOW_REDIRECTS => false,
    ],
    
    /*
     * The sitemap generator can execute JavaScript on each page so it will
     * discover links that are generated by your JS scripts. This feature
     * is powered by headless Chrome.
     */
    'execute_javascript' => false,
    
    /*
     * The package will make an educated guess as to where Google Chrome is installed. 
     * You can also manually pass it's location here.
     */
    'chrome_binary_path' => '',

    /*
     * The sitemap generator uses a CrawlProfile implementation to determine
     * which urls should be crawled for the sitemap.
     */
    'crawl_profile' => Profile::class,
    
];

Creating Sitemap Command

You can easily create an artisan command to create a sitemap and schedule it to run frequently. This will ensure that new pages and content types will be automatically picked up. To create a sitemap command run the following command.

php artisan make:command GenerateSitemap

Update the sitemap command with the following code.

app/Console/Commands/GenerateSitemap.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
use Spatie\Sitemap\SitemapGenerator;


use App\Models\Post;

class GenerateSitemap extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sitemap:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Automatically Generate an XML Sitemap';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        SitemapGenerator::create(config('app.url'))
          ->writeToFile(public_path('sitemap.xml'));
      
      /*
      $postsitmap = Sitemap::create();

        Post::get()->each(function (Post $post) use ($postsitmap) {
            $postsitmap->add(
                Url::create("/{$post->slug}")
                    ->setPriority(0.9)
                    ->setChangeFrequency(Url::CHANGE_FREQUENCY_MONTHLY)
            );
        });

        $postsitmap->writeToFile(public_path('sitemap.xml')); 
         */
    }
}

Scheduled Command in Console Kernel

Now we nee to register this command to kernel for automatically generate XML sitemap. It can be scheduled in the console kernel to be run daily.

app/Console/Kernel.php

// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    ...
    $schedule->command('sitemap:generate')->daily();
    ...
}

We are all set, the sitemap is automatically set to be run daily. To set for now we are going to run the command to generate our sitemap manually by running the following command.

php artisan sitemap:generate

The above command will generate the sitemap.xml in public directory.

Run the following command to start the Artisan development server for laravel.

php artisan serve

And open the following link in any web browser to open the sitemap.

http://127.0.0.1:8000/sitemap.xml

Also you can create a live server command from route in order to test it:

* Put this code into route->web.php

Route::get('/generate-sitemap', function() {
    $exitCode = Artisan::call('sitemap:generate');
    return "sitemap generated"; 
}); 

Hopefully it should work now! Still if you see any trouble feel tree comment below.

Tags
Share :


+91 8447 525 204 Request Estimate