This commit is contained in:
f4ilji
2024-11-05 15:08:08 +05:00
parent e3af1778f0
commit 4b693240e0
41 changed files with 2106 additions and 413 deletions
@@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers;
use App\Enums\PostStatus;
use App\Models\Page;
use App\Models\Post;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
class GenerateSitemapController extends Controller
{
public function index()
{
$sitemap = Sitemap::create();
$this->generatePages($sitemap);
$this->generatePosts($sitemap);
$sitemap->writeToFile(public_path('sitemap.xml'));
}
protected function generatePages(Sitemap $sitemap)
{
$pages = Page::query()
->where('is_visible', true)
->where('code', 200)
->get();
$this->addUrlsToSitemap($sitemap, $pages, function($page) {
return [
'path' => "/{$page->path}",
'lastModificationDate' => $page->updated_at,
'priority' => 0.5,
];
});
}
protected function generatePosts(Sitemap $sitemap)
{
$posts = Post::query()
->where('status', PostStatus::PUBLISHED)
->get();
$this->addUrlsToSitemap($sitemap, $posts, function($post) {
return [
'path' => "/news/{$post->slug}",
'lastModificationDate' => $post->updated_at,
'priority' => 0.5,
];
});
}
protected function addUrlsToSitemap(Sitemap $sitemap, $items, callable $callback)
{
foreach ($items as $item) {
$urlData = $callback($item);
$sitemap->add(Url::create($urlData['path'])
->setLastModificationDate($urlData['lastModificationDate'])
->setPriority($urlData['priority']));
}
}
}