Skip to content

Instantly share code, notes, and snippets.

@ekrist1
Created September 11, 2018 13:29
Show Gist options
  • Save ekrist1/bec76d144bcbebbf0f8f371386dda920 to your computer and use it in GitHub Desktop.
Save ekrist1/bec76d144bcbebbf0f8f371386dda920 to your computer and use it in GitHub Desktop.
Laravelium Sitemap Example
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Item;
use Illuminate\Support\Facades\URL;
use Carbon\Carbon;
class GenerateSitemap implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// resolve sitemap from Service Container
$sitemap = resolve('sitemap');
// counters
$counter = 0;
$sitemapCounter = 0;
// add every product to multiple sitemaps with one sitemap index
foreach (Item::with('category')->cursor() as $item) {
if ($counter == 50000) {
// generate new sitemap file
$sitemap->store('xml', 'sitemap-' . $sitemapCounter);
// add the file to the sitemaps array
$sitemap->addSitemap(secure_url('sitemap-' . $sitemapCounter . '.xml'));
// reset items array (clear memory)
$sitemap->model->resetItems();
// reset the counter
$counter = 0;
// count generated sitemap
$sitemapCounter++;
}
// add product to items array
$sitemap->add(config('app.url') . '/vurder/'. $item->category->slug . '/' . $item->slug, $item->created_at->tz('UTC')->toAtomString(), 0.9, 'weekly');
// count number of elements
$counter++;
}
// you need to check for unused items
if (!empty($sitemap->model->getItems())) {
// generate sitemap with last items
$sitemap->store('xml', 'sitemap-' . $sitemapCounter);
// add sitemap to sitemaps array
$sitemap->addSitemap(secure_url('sitemap-' . $sitemapCounter . '.xml'));
// reset items array
$sitemap->model->resetItems();
}
// generate new sitemapindex that will contain all generated sitemaps above
$sitemap->store('sitemapindex', 'sitemap');
}
}
@ekrist1
Copy link
Author

ekrist1 commented Sep 11, 2018

This gist shows how to generate big sitemaps with Laravelium Sitemap (1M ++ records).

  1. create a new job (php artisan make:job GenerateJob)
  2. call the job from a controller or generate a scheduled command

https://gitlab.com/Laravelium/Sitemap

Laravelium Sitemap is the best package for Laravel I have found for creating large sitemaps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment