mamdouh asked this 2 years ago

Adding a sitemap to a Laravel application

Without any additional plugins what is the easiest way to generate a sitemap for your Laravel application?

Most solutions around suggest using a plugin like laravel-sitemap package by RoumenDamianoff.


sonja 2 years ago

Lets say, you have a route corresponding controller method for generating sitemap.

Inside your controller you can just create the xml file structure:

$sitemapHeader  = '<?xml version="1.0" encoding="utf-8"?>'."\n";
		$sitemapHeader .= '<urlset ';
		$sitemapHeader .= 'xmlns="" ';
		$sitemapHeader .= 'xmlns:xsi="" ';
		$sitemapHeader .= 'xsi:schemaLocation=" ';
		$sitemapHeader .= '"';
		$sitemapHeader .= '>';


This would be the header.

Now inside you have to put your urls wrapped in



This is the bare minimum info. You can include more information like last modified, priority etc



Now you may use your Laravel model to generate dynamic URLs.

$articles = Article::all();
foreach ($articles as $article) {
$title = $article -> slug;
$str = '<url>'."\n";
$str .= '<loc>';
$str .= ''.$title;
$str .= '</loc>'."\n";
$str .= '</url>'."\n";
$sitemap .= $str;


Now add the header and footer to the set of URLs.

$sitemapFooter ='</urlset>';
$sitemap = $sitemapHeader.$sitemap;
$sitemap = $sitemap.$sitemapFooter;


This can be written to a file in a desired location.

//Write Sitemap to file
$filename = 'sitemap.xml';
file_put_contents($filename, $sitemap);