Sitemap is one of the important parts of off-page SEO. It's call the entire overview of a website. If you reached here to read this post, probably you are looking for how to make a dynamic sitemap for your Laravel website. There are some packages for laravel sitemap creation but here I'll show you how to make a simple dynamic sitemap without using Laravel sitemap package. I can assure you, sitemap creation with Laravel is a very easy process with few steps. I'll show you step by step how you can make your laravel website sitemap easily. Let's start.
Define a simple get route in web.php file for handling the sitemap.xml request.
Route::get('sitemap.xml','SitemapController@index');
Make a sitemap controller by artisan command like php artisan make:controller SitemapController
and do code for making a sitemap.
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Http\Request;
class SitemapController extends Controller
{
public function index(Request $r)
{
$posts = Post::orderBy('id','desc')->where('post_status', 'Publish')->get();
return response()->view('sitemap', compact('posts'))
->header('Content-Type', 'text/xml');
}
}
Make a sitemap.blade.php view in resources/views directory.
<?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>{{url($post->slug_url)}}</loc>
<lastmod>{{ gmdate('Y-m-d\TH:i:s\Z',strtotime($post->updated_at)) }}</lastmod>
<changefreq>daily</changefreq>
<priority>0.6</priority>
</url>
@endforeach
</urlset>
Yah, it's simple. Our sitemap is ready. Just browse http://example.com/sitemap.xml
Now you can submit your website sitemap to search engine like Google, Bing, Yandex, Yahoo etc to index their search result set. Hope this 3 steps simple dynamic sitemap creation with Laravel will help you to make your won. If this is helpful, then please share this post with others.