9

I am developing a Laravel application. Now, I am trying to implement the sitemap for my website using this package, https://github.com/spatie/laravel-sitemap. But when I generate sitemap.xml, no paths are included in the file.

I installed the package running the Composer command

composer require spatie/laravel-sitemap

Then I published the Composer.

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

In the routes/web.php, I added this.

Route::get('sitemap', function () {
    SitemapGenerator::create('http://app.localhost/')->writeToFile('sitemap.xml');
    return "Sitemap generated".
});

When I run the code and sitemap.xml is generated. When I opened the sitemap.xml, that is all I found in it.

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
</urlset>

I have many routes in the web.php. What is wrong and how can fix it?

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

4 Answers4

3

You can manually add other urls like below and when you run it, the links will be added to your sitemap file:

use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;

 Route::get('sitemap', function () {
    SitemapGenerator::create('https://vesicash.com/')->getSitemap()
    ->add(Url::create('/link1')->setPriority(0.5))
    ->add(Url::create('/link2')->setPriority(0.5))
    ->add(Url::create('/link3')->setPriority(0.5))
    ->add(Url::create('/privacy')->setPriority(0.5))
    ->writeToFile('sitemap.xml');
    return "Sitemap Generated";
});
Ehi
  • 168
  • 1
  • 2
  • 12
2

This is how I solved this problem:

I just made sure that the APP_URL was set properly in .env file.

I added, for example: https://example.com/ and boom it worked.

This should also work on your local pc as well.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
1

When I did it first time it looked same for me.

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
</urlset>

I think you did it on your local pc.

So first, you can test with this url.

SitemapGenerator::create("https://spatie.be/en")
            ->writeToFile(public_path('sitemap.xml'));

If it works well, then I believe it will work on server too. In my case it worked on server, while it was same result with you on my local.

LoveCoding
  • 1,121
  • 2
  • 12
  • 33
0

Solution to anyone, don't panic

the problem is when u clear config or when u run php artisan optimize:clear

the url will be null or ''

so solution is : (config('app.url') ?? 'http://www.myspecialdomain.com')

this will check if url exist if not it will use provided url.

Have a good day

Joukhar
  • 724
  • 1
  • 3
  • 18