How to Generate sitemap in laravel

Deven Rathore 5 min read
How to Generate sitemap in laravel
In this article we will learn how to generate sitemap with larvel via an easy and automate process so lets get started
A simple sitemap generator for Laravel. is best package to make his procesess easy and automate tested with laravel 5 lets find out how to use it first you have to install it via command linde

Installation

Run the following command and provide the latest stable version (e.g v2.5.3) :

composer require roumen/sitemap

or add the following to your composer.json file :

"roumen/sitemap": "2.5.*"

Then register this service provider with Laravel :

'RoumenSitemapSitemapServiceProvider',

Publish configuration file (OPTIONAL) :

php artisan vendor:publish

Example: How to create dynamic sitemap

Route::get('sitemap', function(){

    // create new sitemap object
    $sitemap = App::make("sitemap");

    // set cache (key (string), duration in minutes (Carbon|Datetime|int), turn on/off (boolean))
    // by default cache is disabled
    $sitemap->setCache('laravel.sitemap', 3600);

    // check if there is cached sitemap and build new only if is not
    if (!$sitemap->isCached())
    {
         // add item to the sitemap (url, date, priority, freq)
         $sitemap->add(URL::to('/'), '2012-08-25T20:10:00+02:00', '1.0', 'daily');
         $sitemap->add(URL::to('page'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly');

         // add item with translations (url, date, priority, freq, images, title, translations)
         $translations = [
                           ['language' => 'fr', 'url' => URL::to('pageFr')],
                           ['language' => 'de', 'url' => URL::to('pageDe')],
                           ['language' => 'bg', 'url' => URL::to('pageBg')],
                         ];
         $sitemap->add(URL::to('pageEn'), '2015-06-24T14:30:00+02:00', '0.9', 'monthly', [], null, $translations);

         // add item with images
         $images = [
                     ['url' => URL::to('images/pic1.jpg'), 'title' => 'Image title', 'caption' => 'Image caption', 'geo_location' => 'Plovdiv, Bulgaria'],
                     ['url' => URL::to('images/pic2.jpg'), 'title' => 'Image title2', 'caption' => 'Image caption2'],
                     ['url' => URL::to('images/pic3.jpg'), 'title' => 'Image title3'],
                   ];
         $sitemap->add(URL::to('post-with-images'), '2015-06-24T14:30:00+02:00', '0.9', 'monthly', $images);

         // get all posts from db
         $posts = DB::table('posts')->orderBy('created_at', 'desc')->get();

         // add every post to the sitemap
         foreach ($posts as $post)
         {
            $sitemap->add($post->slug, $post->modified, $post->priority, $post->freq);
         }
    }

    // show your sitemap (options: 'xml' (default), 'html', 'txt', 'ror-rss', 'ror-rdf')
    return $sitemap->render('xml');

});

 

Example: How to create dynamic sitemap with image tags

In this example the posts model has a belongsToMany relationship to images.

Route::get('sitemap', function(){

    // create new sitemap object
    $sitemap = App::make("sitemap");

    // set cache (key (string), duration in minutes (Carbon|Datetime|int), turn on/off (boolean))
    // by default cache is disabled
    $sitemap->setCache('laravel.sitemap', 3600);

    // check if there is cached sitemap and build new only if is not
    if (!$sitemap->isCached())
    {
         // add item to the sitemap (url, date, priority, freq)
         $sitemap->add(URL::to('/'), '2012-08-25T20:10:00+02:00', '1.0', 'daily');
         $sitemap->add(URL::to('page'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly');

         // get all posts from db, with image relations
         $posts = DB::table('posts')->with('images')->orderBy('created_at', 'desc')->get();

         // add every post to the sitemap
         foreach ($posts as $post)
         {
            // get all images for the current post
            $images = array();
            foreach ($post->images as $image) {
                $images[] = array(
                    'url' => $image->url,
                    'title' => $image->title,
                    'caption' => $image->caption
                );
            }

            $sitemap->add($post->slug, $post->modified, $post->priority, $post->freq, $images);
         }
    }

    // show your sitemap (options: 'xml' (default), 'html', 'txt', 'ror-rss', 'ror-rdf')
    return $sitemap->render('xml');

});

 

How to use multiple sitemaps with sitemap index

// sitemap with posts
Route::get('sitemap-posts', function()
{
    // create sitemap
    $sitemap_posts = App::make("sitemap");

    // set cache
    $sitemap_posts->setCache('laravel.sitemap-posts', 3600);

    // add items
    $posts = DB::table('posts')->orderBy('created_at', 'desc')->get();

    foreach ($posts as $post)
    {
        $sitemap_posts->add($post->slug, $post->modified, $post->priority, $post->freq);
    }

    // show sitemap
    return $sitemap_posts->render('xml');
});
// sitemap with tags
Route::get('sitemap-tags', function()
{
    // create sitemap
    $sitemap_tags = App::make("sitemap");

    // set cache
    $sitemap_tags->setCache('laravel.sitemap-tags', 3600);

    // add items
    $tags = DB::table('tags')->get();

    foreach ($tags as $tag)
    {
        $sitemap_tags->add($tag->slug, null, '0.5', 'weekly');
    }

    // show sitemap
    return $sitemap_tags->render('xml');
});
// sitemap index
Route::get('sitemap', function()
{
    // create sitemap
    $sitemap = App::make("sitemap");

    // set cache
    $sitemap->setCache('laravel.sitemap-index', 3600);

    // add sitemaps (loc, lastmod (optional))
    $sitemap->addSitemap(URL::to('sitemap-posts'));
    $sitemap->addSitemap(URL::to('sitemap-tags'));

    // show sitemap
    return $sitemap->render('sitemapindex');
});

How to use multiple sitemaps with sitemap index (with store() method)

Route::get('sitemap-store', function()
{
    // create sitemap
    $sitemap_posts = App::make("sitemap");

    // add items
    $posts = DB::table('posts')->orderBy('created_at', 'desc')->get();
    foreach ($posts as $post)
    {
        $sitemap_posts->add($post->slug, $post->modified, $post->priority, $post->freq);
    }

    // create file sitemap-posts.xml in your public folder (format, filename)
    $sitemap_posts->store('xml','sitemap-posts');

    // create sitemap
    $sitemap_tags = App::make("sitemap");

    // add items
    $tags = DB::table('tags')->get();

    foreach ($tags as $tag)
    {
        $sitemap-tags->add($tag->slug, null, '0.5', 'weekly');
    }

    // create file sitemap-tags.xml in your public folder (format, filename)
    $sitemap_tags->store('xml','sitemap-tags');

    // create sitemap index
    $sitemap = App::make ("sitemap");

    // add sitemaps (loc, lastmod (optional))
    $sitemap->addSitemap(URL::to('sitemap-posts'));
    $sitemap->addSitemap(URL::to('sitemap-tags'));

    // create file sitemap.xml in your public folder (format, filename)
    $sitemap->store('sitemapindex','sitemap');
});

Example: How to generate sitemap file

Route::get('mysitemap', function(){

    // create new sitemap object
    $sitemap = App::make("sitemap");

    // add items to the sitemap (url, date, priority, freq)
    $sitemap->add(URL::to(), '2012-08-25T20:10:00+02:00', '1.0', 'daily');
    $sitemap->add(URL::to('page'), '2012-08-26T12:30:00+02:00', '0.9', 'monthly');

    // get all posts from db
    $posts = DB::table('posts')->orderBy('created_at', 'desc')->get();

    // add every post to the sitemap
    foreach ($posts as $post)
    {
        $sitemap->add($post->slug, $post->modified, $post->priority, $post->freq);
    }

    // generate your sitemap (format, filename)
    $sitemap->store('xml', 'mysitemap');
    // this will generate file mysitemap.xml to your public folder