Hi In this article I am going to show how to create a dynamic sitemap file for SEO in Laravel.

First, create a file named sitemap.blade.php in the views folder. sample sitemap file looks below, and paste the same into your blade file.

 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

<!-- created with Free Online Sitemap Generator www.xml-sitemaps.com -->

<url>

<loc>http://127.0.0.1:8000/</loc>

<lastmod>2023-09-06T07:30:00+00:00</lastmod>

<priority>1.00</priority>

</url>

<url>

<loc>http://127.0.0.1:8000/interviews/laravel</loc>

<lastmod>2023-09-04T07:51:39+00:00</lastmod>

<changefreq>weekly</changefreq>

<priority>0.80</priority>

</url>

</urlset>

Now create a route, go to the web.php file, and create a route like below.

Route::get('sitemap.xml',function(){

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

        'posts' => Blog::all(),

        'interviewcat' =>InterviewCategory::all()

    ])->header('content-type','text/xml');

});

Here you can see we are passing multiple array data like posts and interviewcat to view  sitemap.blade.php file.

Your final sitemap file will look like below.

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

<!-- created with Free Online Sitemap Generator www.xml-sitemaps.com -->

<url>

<loc>http://127.0.0.1:8000/</loc>

<lastmod>2023-09-06T07:30:00+00:00</lastmod>

<priority>1.00</priority>

</url>

@foreach($posts as $post)

<url>

<loc>{{url('/')}}/tutorial/{{$post->slug}}</loc>

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

<changefreq>weekly</changefreq>

<priority>0.80</priority>

</url>

@endforeach


 

@foreach($interviewcat as $item)

<url>

<loc>{{url('/')}}/interviews/{{$item->slug}}</loc>

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

<changefreq>weekly</changefreq>

<priority>0.80</priority>

</url>

@endforeach

</urlset>

Now run the command php artisan serve and check the url http://127.0.0.1:8000/sitemap.xml.

Thanks for reading……..

Leave a Comment
No Comments found