Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
Last active September 22, 2023 01:54
Show Gist options
  • Save sam-ngu/451e013f1942ef9663ce0f71ff363575 to your computer and use it in GitHub Desktop.
Save sam-ngu/451e013f1942ef9663ce0f71ff363575 to your computer and use it in GitHub Desktop.
Laravel php artisan generate sitemap command
<?php
namespace App\Console\Commands;
use App\Models\Course;
use Illuminate\Console\Command;
use Spatie\Browsershot\Browsershot;
use Spatie\Crawler\Crawler;
use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\Tags\Url;
class GenerateSitemap extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'generate sitemap using spatie\'s sitemap package';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// adding our own browsershot to add the noSandbox option to chrome, since it is run by the root user in docker container
$browsershot = (new Browsershot())->noSandbox()->ignoreHttpsErrors();
$path = public_path('sitemap.xml');
$sitemap = SitemapGenerator::create("https://nginx/")
->configureCrawler(function (Crawler $crawler) use ($browsershot){
$crawler->setBrowsershot($browsershot);
})
->hasCrawled(function (Url $url){
// overwriting the base nginx url in our sitemap. Without this the url display in the xml will look something like this: https://nginx/uri
$uri = implode('/', $url->segments());
$url->setUrl(config('app.url') . '/' . $uri);
return $url;
})
->getSitemap()
// adding the base slug routes
->add(Url::create('/courses')->setPriority(0.9))
;
// for some reasons laravel sitemap can only detect static pages. This is a workaround to add slug routes
$courses = Course::all();
$courses->each(function ($course) use (&$sitemap){
$sitemap->add('/courses/' . $course->slug );
});
$sitemap->writeToFile($path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment