Files
citrus/app/Http/Controllers/SitemapController.php
T

113 lines
3.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Page;
use App\Models\Blog;
use App\Models\Product;
use Illuminate\Http\Response;
class SitemapController extends Controller
{
public function index(): Response
{
$urls = [];
$activeLanguages = [];
if (class_exists(\App\Models\Language::class)) {
$activeLanguages = \App\Models\Language::where('is_active', true)->get();
}
$getAlternates = function (string $baseUrl) use ($activeLanguages) {
$alternates = [];
foreach ($activeLanguages as $lang) {
$connector = str_contains($baseUrl, '?') ? '&' : '?';
$alternates[] = [
'hreflang' => $lang->code,
'href' => $baseUrl . $connector . 'locale=' . $lang->code,
];
}
$alternates[] = [
'hreflang' => 'x-default',
'href' => $baseUrl,
];
return $alternates;
};
// 1. Static & Main Pages
$homeUrl = url('/');
$urls[] = [
'loc' => $homeUrl,
'alternates' => $getAlternates($homeUrl),
'lastmod' => now()->startOfDay()->toAtomString(),
'changefreq' => 'daily',
'priority' => '1.0',
];
$blogIndexUrl = route('blog.index');
$urls[] = [
'loc' => $blogIndexUrl,
'alternates' => $getAlternates($blogIndexUrl),
'lastmod' => now()->startOfDay()->toAtomString(),
'changefreq' => 'weekly',
'priority' => '0.8',
];
$careerIndexUrl = route('career.index');
$urls[] = [
'loc' => $careerIndexUrl,
'alternates' => $getAlternates($careerIndexUrl),
'lastmod' => now()->startOfMonth()->toAtomString(),
'changefreq' => 'monthly',
'priority' => '0.5',
];
// 2. Dynamic Pages
$pages = Page::where('status', 'published')
->where('is_homepage', false)
->get();
foreach ($pages as $page) {
$pageUrl = url($page->slug);
$urls[] = [
'loc' => $pageUrl,
'alternates' => $getAlternates($pageUrl),
'lastmod' => $page->updated_at->toAtomString(),
'changefreq' => 'weekly',
'priority' => '0.7',
];
}
// 3. Blog Posts
if (class_exists(Blog::class)) {
$posts = Blog::published()->get();
foreach ($posts as $post) {
$postUrl = route('blog.show', $post->slug);
$urls[] = [
'loc' => $postUrl,
'alternates' => $getAlternates($postUrl),
'lastmod' => $post->updated_at->toAtomString(),
'changefreq' => 'weekly',
'priority' => '0.6',
];
}
}
// 4. Products
if (class_exists(Product::class)) {
$products = Product::where('is_active', true)->get();
foreach ($products as $product) {
$productUrl = route('products.show', $product->slug);
$urls[] = [
'loc' => $productUrl,
'alternates' => $getAlternates($productUrl),
'lastmod' => $product->updated_at->toAtomString(),
'changefreq' => 'weekly',
'priority' => '0.7',
];
}
}
return response()->view('sitemap', compact('urls'))
->header('Content-Type', 'text/xml');
}
}