skip to Main Content

I am trying to add sitemap.xml file for an laravel website. I am using laravel version 9. I tried to search on google and youtube but not able to find any solution.

I have created a sitemap.xml file and I have moved sitemap.xml file to the public directory and I have added the route in the routes folder/directory like this to the file web.php where other routes are defined:

Route::get("sitemap.xml" , function () {
return IlluminateSupportFacadesRedirect::to('sitemap.xml');
 });

I have also tried to added the following code to the routes folder/directory like this :

Route::get('sitemap.xml',function() {
return response()->view('sitemap')
->header('Content-Type', 'xml');
});

Now open the xml file through url: https://www.example.com/sitemap.xml, I get 500
SERVER ERROR.

2

Answers


  1. You cannot link to a file, with a view method call. Put the file in the storage folder, and then use the file call to actually serve the file.

    return response()->file('sitemap.xml');
    
    Login or Signup to reply.
  2. If you want to generate dynamically your sitemap and handle it from a blade view, you could make it like that:

    Route::get('sitemap.xml', [SiteMapController::class, 'sitemap'])->name('sitemap');
    

    Then in the SitemapController do the dynamic stuff and return the blade view:

    $models = Model::all();
    return response()->view('sitemap', compact('models'))->header('Content-Type', 'text/xml');
    

    And the sitemap.blade.php in the views folder:

    <?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        @foreach ($models as $model)
        <url>
            <loc>{{ route('models.show', $model) }}</loc>
        </url>
        @endforeach
    </urlset>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search