How To Create Dynamic Sitemap In Laravel

In this article, we will see how to create a dynamic sitemap in laravel. As we know sitemap is very important part of SEO. A sitemap is a list of pages of a website within a single domain. Here we will create a dynamic XML sitemap in laravel. a sitemap is a blueprint of your website that can help to search engines find, crawl and index all of your website's content.

So, let's see generate a dynamic sitemap in laravel 8, create a dynamic XML sitemap in laravel, dynamic sitemap generator in laravel 8, how to generate sitemap in PHP, generate a dynamic sitemap in laravel, sitemap generator in laravel 8, laravel XML sitemap generator.

.Here, we are using a sitemap package to generate a dynamic sitemap in laravel.

composer require watson/sitemap

To publish the configuration file for the sitemap package. So, run below the artisan command and publish the package.

php artisan config:publish watson/sitemap

php artisan vendor:publish --provider="Watson\Sitemap\SitemapServiceProvider"

Here, you need to add tags for each item in your sitemap using Sitemap::addTag($location, $lastModified, $changeFrequency, $priority).

And we can return the sitemap with Sitemap::renderSitemap().

$lastModified variable will be parsed and converted to the right format for the sitemap.

If you want to get raw XML then simply call Sitemap::xml().

Example :

namespace App\Http\Controllers;

use Post;
use Sitemap;

class SitemapsController extends Controller
{
    public function posts()
    {
        $posts = Post::all();

        foreach ($posts as $post) {
            Sitemap::addTag(route('posts.show', $post), $post->updated_at, 'daily', '0.6');
        }

        return Sitemap::render();
    }
}

 

 

Image Sitemap:

Parameters :  $tag->addImage($location, $caption, $geoLocation, $title, $licenceUrl);

For Image, you can use the addImage() function like the below code example.

namespace App\Http\Controllers;

use Page;
use Sitemap;

class SitemapsController extends Controller
{
    public function pages()
    {
        $pages = Page::all();

        foreach ($pages as $page) {
            $tag = Sitemap::addTag(route('pages.show', $page), $page->updated_at, 'daily', '0.8');

            foreach ($page->images as $image) {
                $tag->addImage($image->url, $image->caption);
            }
        }

        return Sitemap::render();
    }
}

 


You might also like :

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS