Generate dynamic sitemap in Laravel - SEO


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.

 

Steps for Sitemap creation in Laravel

  1. Define route
  2. Make a sitemap controller
  3. Make XML response for render sitemap.

 

Step 01: Define Route

Define a simple get route in web.php file for handling the sitemap.xml request.

Route::get('sitemap.xml','SitemapController@index');

 

Step 02: Make a sitemap controller

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');

    }
}

 

Step 03: Make XML response for render sitemap

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.

 

Share on



Related Post - Latest Post


Laravel Barcode generation tutorial

Ultimate Laravel SEO guide in 2020

Generate SEO friendly URL in Laravel

Dynamic SEO meta-tags in Laravel website