First question is in your mind is why we need this Sitemap?
let be describe you first, Sitemap ideally is a file that ends with a .xml extension; it is a simple file that contains the important website pages and allows the webmaster to inform search engines what pages are available for crawling.
This sitemap file is not just limited to laravel only, no matter what technology you are using but make sure you must generate and add a sitemap xml file to inform search engines.
Here we all know about SEO, and this is not just a keyword; rather, this word decides the popularity of web applications. SEO decides the ranking of your site on the search engines, That is why we need sitemap for our website.
Sitemap design like this:
<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://www.readytocode.net/</loc> <lastmod>2022-03-11</lastmod> <changefreq>monthly</changefreq> <priority>0.8</priority> </url> </urlset>
Describe :
- It starts with an opening <urlset> tag relatively with ending </urlset>closing tag.
- The xmlns property used to define the namespace prefix inside the <urlset> tag.
- The xml contains url entry for every url that needs to be added in the Sitemap.
- The loc property is the child value of url which holds the web page url.
- The lastmod attribute is the child element of url, which reveals when was the page last modified.
- The changefreq and priority attributes are relative child values of the url property; these props let search engine about the crawling priority and update frequencies.
Now our Reading part is completed, lets jump on Coding .
Step 1.
Install a fresh Laravel project.
Step 2.
Attach with database.
Step 3.
Create some dummy data.
Step 4.
Create Controller for Sitemap and Route for this.
php artisan make:controller SitemapXml
Routes/web.php
Route::get('/sitemap.xml', [SitemapXml::class, 'index']);
Step 5.
Now we will add method index in controller file for the route which we connected.
public function index(){ $urls = Post::all(); return response()->view('sitemap', [ 'urls' => $urls ])->header('Content-Type', 'text/xml'); }
And also i will create a blade file with named sitemap.blade.php
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> @foreach ($urls as $url) <url> <loc>{{ url('/') }}/{{ $url->slug }}</loc> <lastmod>{{date('Y-m-d', strtotime($url->updated_at))}}</lastmod> <changefreq>weekly</changefreq> <priority>0.8</priority> </url> @endforeach </urlset>
Step 6.
All done just run the project and open your new route URL,
php artisan serve
URL will be
http://127.0.0.1:8000/sitemap.xml