How to Create Sitemap XML in Laravel 7/6?

Laravel 6 , Laravel , Laravel 7

Nicesnippets

2438

08-02-2020


Hi Guys,

In this example, you will learn create sitemap in laravel. This tutorial will give you simple example of sitemap generator in laravel.

I explained simply step by step laravel sitemap example Here you will learn sitemap.xml in laravel. So, let's follow few step to create example of sitemap in laravel.

Google gives the size of the site as one of the reasons why this is possible and need for a sitemap, Your website has too many pages that are not linked to each other or are isolated. This means they are not referencing each other and by listing these files in a sitemap decreases the chance of Google not overlooking these pages,

You will follow bellow step by step to create sitemap in your laravel app.

Step 1 : Create Route

In this step, you will put the bellow route code in web.php file

routes/web.php

Route::get('/sitemap.xml', 'SiteMapController@index');

Step 2 : Create Controller and Method

Second step in, You can create controller and create index mehtod in controller.

app/http/controllers/SiteMapController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;

class SiteMapController extends Controller

{

public function index()

{

$posts= Post::latest()->get();

return response()->view('sitemap.index', [

'posts' => $posts,

])->header('Content-Type', 'text/xml');

}

}

Step 3 : Create View File

Last step in You will create view file in sitemap directory. and put the bellow code in index.blade.php file.

resources/views/sitemap/index.blade.php

<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

@foreach ($posts as $post)

<url>

<loc>https://nicesnippets.com/{{ $post->title }}</loc>

<lastmod>{{ $post->created_at->tz('UTC')->toAtomString() }}</lastmod>

<changefreq>weekly</changefreq>

<priority>0.6</priority>

</url>

@endforeach

</urlset>

If everything done than you can run your application and use following credentials:

php artisan serve

Open following link:

http://localhost:8000/sitemap.xml

It will help you...