init
This commit is contained in:
50
web10/app/Http/Controllers/SitemapController.php
Normal file
50
web10/app/Http/Controllers/SitemapController.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Article;
|
||||
use App\Models\Category;
|
||||
use App\Models\Product;
|
||||
use App\Models\Tag;
|
||||
|
||||
class SitemapController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$baseUrl = rtrim(config('app.url'), '/');
|
||||
|
||||
$urls = [
|
||||
'/',
|
||||
'/categories',
|
||||
'/tags',
|
||||
'/articles',
|
||||
'/about',
|
||||
'/contact',
|
||||
];
|
||||
|
||||
$categories = Category::all()->map(fn ($c) => "/category/{$c->slug}")->all();
|
||||
$tags = Tag::all()->map(fn ($t) => "/tag/{$t->slug}")->all();
|
||||
$products = Product::published()->get()->map(fn ($p) => "/product/{$p->slug}")->all();
|
||||
$articles = Article::published()->get()->map(fn ($a) => "/article/{$a->slug}")->all();
|
||||
|
||||
$allUrls = array_merge($urls, $categories, $tags, $products, $articles);
|
||||
|
||||
$xml = new \XMLWriter();
|
||||
$xml->openMemory();
|
||||
$xml->startDocument('1.0', 'UTF-8');
|
||||
$xml->startElement('urlset');
|
||||
$xml->writeAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
|
||||
|
||||
foreach ($allUrls as $path) {
|
||||
$xml->startElement('url');
|
||||
$xml->writeElement('loc', $baseUrl . $path);
|
||||
$xml->endElement();
|
||||
}
|
||||
|
||||
$xml->endElement();
|
||||
$xml->endDocument();
|
||||
|
||||
return response($xml->outputMemory(), 200)
|
||||
->header('Content-Type', 'application/xml');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user