Skip to content

Instantly share code, notes, and snippets.

@djeraseit
Forked from ekrist1/GenerateSitemap.php
Created July 20, 2021 23:38
Show Gist options
  • Save djeraseit/4ba2b54ad07d2cb86188d173a0f0cb22 to your computer and use it in GitHub Desktop.
Save djeraseit/4ba2b54ad07d2cb86188d173a0f0cb22 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');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment