File: /home/armgroup/libs/app/Console/Commands/GenerateSitemap.php
<?php
namespace App\Console\Commands;
use App\Models\Article;
use App\Models\Brand;
use App\Models\Category;
use App\Models\Page;
use App\Models\Product;
use App\Models\Tag;
use Illuminate\Console\Command;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\SitemapIndex;
class GenerateSitemap extends Command
{
protected $signature = 'sitemap:generate';
protected $description = 'Generate the sitemap.';
public function handle()
{
SitemapIndex::create()
->add('/products_sitemap.xml')
->add('/categories_sitemap.xml')
->add('/brands_sitemap.xml')
->add('/tags_sitemap.xml')
->add('/articles_sitemap.xml')
->add('/pages_sitemap.xml')
->writeToFile(public_path('sitemap.xml'));
// Products
$products_sitemap = Sitemap::create();
Product::query()->where('status', true)->latest()->get(['id', 'slug'])
->each(function (Product $product) use ($products_sitemap) {
$products_sitemap->add(route('products.show', [$product->slug]));
});
$products_sitemap->writeToFile(public_path('products_sitemap.xml'));
// Categories
$categories_sitemap = Sitemap::create();
Category::query()->where('status', true)->where('type', Product::class)->latest()->get(['id', 'slug'])
->each(function (Category $category) use ($categories_sitemap) {
$categories_sitemap->add(route('categories.show', [$category->slug]));
});
$categories_sitemap->writeToFile(public_path('categories_sitemap.xml'));
// Brands
$brands_sitemap = Sitemap::create();
Brand::query()->latest()->get(['id', 'slug'])
->each(function (Brand $brand) use ($brands_sitemap) {
$brands_sitemap->add(route('brands.show', [$brand->slug]));
});
$brands_sitemap->writeToFile(public_path('brands_sitemap.xml'));
// Tags
$tags_sitemap = Sitemap::create();
Tag::query()->latest()->get(['id', 'slug'])
->each(function (Tag $tag) use ($tags_sitemap) {
$tags_sitemap->add(route('tags.show', [$tag->slug]));
});
$tags_sitemap->writeToFile(public_path('tags_sitemap.xml'));
// Articles
$articles_sitemap = Sitemap::create();
Article::query()->where('status', true)->latest()->get(['id', 'slug'])
->each(function (Article $article) use ($articles_sitemap) {
$articles_sitemap->add(route('articles.show', [$article->slug]));
});
$articles_sitemap->writeToFile(public_path('articles_sitemap.xml'));
// Pages
$pages_sitemap = Sitemap::create();
Page::query()->where('status', true)->latest()->get(['id', 'slug'])
->each(function (Page $page) use ($pages_sitemap) {
$pages_sitemap->add(route('pages.show', [$page->slug]));
});
$pages_sitemap->writeToFile(public_path('pages_sitemap.xml'));
}
}