Generate Sitemap in Laravel

By Imran Iqbal In Cache, Packages, Views, Laravel Tips - - Comments(0) - Views(10112)
Tags : sitemap, laravel sitemap, generate sitemap in laravel, roumen/sitemap

What is Sitemap ?

A site map (or sitemap) is a list of pages of a web site accessible to crawlers or users. It can be either a document in any form used as a planning tool for Web design, or a Web page that lists the pages on a Web site, typically organized in hierarchical fashion.

As per google 

Ideally, if your site’s pages are properly linked, our web crawlers can usually discover most of your site. Even so, a sitemap is a helpful tool that can improve the crawling of your site, particularly if your site meets one of the following criteria:

  • Your site is really large. As a result, it’s more likely Google web crawlers might overlook crawling some of your new or recently updated pages.
  • Your site has a large archive of content pages that are isolated or well not linked to each other. If you site pages do not naturally reference each other, you can list them in a sitemap to ensure that Google does not overlook some of your pages.
  • Your site is new and has few external links to it. Googlebot and other web crawlers crawl the web by following links from one page to another. As a result, Google might not discover your pages if no other sites link to them.
  • Your site uses rich media content, is shown in Google News, or uses other sitemaps-compatible annotations.Google can take additional information from sitemaps into account for search, where appropriate.

Generate Sitemap in Laravel

Generating sitemaps in laravel is not a big deal because Roumen Damianoff already implemented the functionality in the form of the package which we can pull from packagist using composer . what are thinking lets start , pull the package 

php composer require roumen/sitemap

Register service provider , go to app.php and add service provider like below

'Roumen\Sitemap\SitemapServiceProvider',

Now publish config file

php artisan config:publish roumen/sitemap

Mostly crawlers will look for sitemap.xml in your project root which will be available at kodeinfo.com/sitemap.xml , So we will define a route for sitemap.xml

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

});

Now create new sitemap object and add our url's

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

// 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($url,$last_updated, $priority,$frequency,$image,$title);
   $sitemap->add(URL::to('/')."/post/".$post->slug, $post->updated_at, '1', 'weekly',"/uploads/images/$post->featured_image",$post->title);
}

Final step is to render our sitemap file 

return $sitemap->render('xml');

You can also render sitemap in other formats , supported formats are ror-rss , ror-rdf , html , xml , txt and default is xml so you can also call it as below

return $sitemap->render();

Complete code is below

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

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

    // 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($url,$last_updated, $priority,$frequency,$image,$title);
        $sitemap->add(URL::to('/')."/post/".$post->slug, $post->updated_at, '1', 'weekly',"/uploads/images/$post->featured_image",$post->title);
    }

    return $sitemap->render('xml');
});

I have added sitemap on kodeinfo using same package so if you want to see the output click here

You can also store the sitemap using store method 

$sitemap->store('xml', 'sitemap');

Using Cache to store sitemap

If you want to cache sitemap that's a great idea and package provides you this functionality out of the box . We can cache sitemap , if cache is expired then generate new sitemap .

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

Check if cache exists 

// 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
         $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);
         }
}

Alternative to this you can also turn on cache using config file , go to app/config/packages/roumen/sitemap and set your preferred values

<?php

/* Simple configuration file for Laravel Sitemap package */
return array(
    'use_cache' => true,
    'cache_key' => 'kodeinfo.sitemap.',
    'cache_duration' => 3600,
);

You can also generate multiple sitemaps , follow official tutorial here

 

Thanks

KodeInfo

Author

Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

comments powered by Disqus