How to create real time sitemap.xml file in Laravel?
We can create all web pages of our sites to tell Google and other search engines like Bing, Yahoo etc about the organization of our site content. These search engine web crawlers read this file to more intelligently crawl our sites.
Here are the steps that helps you to create real time sitemap.xml file and these steps also helps to create dynamic XML files.
- Firstly we have to create a route for this in your
routes/web.php
file
Example
Route::get('sitemap.xml', 'SitemapController@index')->name('sitemapxml');
- Now you can create SitemapController.php with artisan command
php artisan make:controller SitemapController
- Now you can put this code in your controller
public function index() {
$page = Page::where('status', '=', 1)->get();
return response()->view('sitemap_xml', ['page' => $page])->header('Content-Type', 'text/xml');
} - Now please create a view file in
resources/view/sitemap_xml.blade.php
file with this code - Put this code in that created view file
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<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">
@foreach ($page as $post)
<url>
<loc>{{ url($post->page_slug) }}</loc>
<lastmod>{{ $post->updated_at->tz('UTC')->toAtomString() }}</lastmod>
<priority>0.9</priority>
</url>
@endforeach
</urlset>
BY Best Interview Question ON 06 May 2020