Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
SeoController
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
2 / 2
5
100.00% covered (success)
100.00%
1 / 1
 sitemap
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 robots
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\admin\Product;
6use App\Models\Category;
7use Illuminate\Http\Response;
8
9/**
10 * XML sitemap + robots.txt, both driven by the `seo` settings group
11 * (Settings → SEO & Analytics).
12 */
13class SeoController extends Controller
14{
15    public function sitemap(): Response
16    {
17        abort_unless(settings('seo.sitemap_enabled', true), 404);
18
19        $urls = collect();
20        $urls->push(['loc' => url('/'), 'priority' => '1.0', 'changefreq' => 'daily']);
21
22        Product::query()->select('id', 'updated_at')->latest('id')->limit(5000)->get()
23            ->each(fn ($p) => $urls->push([
24                'loc' => route('product', $p->id),
25                'lastmod' => optional($p->updated_at)->toAtomString(),
26                'changefreq' => 'weekly',
27                'priority' => '0.8',
28            ]));
29
30        Category::query()->select('id', 'name', 'updated_at')->get()
31            ->each(fn ($c) => $urls->push([
32                'loc' => route('category.product', [$c->name, $c->id]),
33                'lastmod' => optional($c->updated_at)->toAtomString(),
34                'changefreq' => 'weekly',
35                'priority' => '0.6',
36            ]));
37
38        $xml = view('seo.sitemap', ['urls' => $urls])->render();
39
40        return response($xml, 200, ['Content-Type' => 'application/xml']);
41    }
42
43    public function robots(): Response
44    {
45        $indexable = (bool) settings('seo.robots_indexable', true);
46
47        $lines = ['User-agent: *'];
48        $lines[] = $indexable ? 'Disallow: /admin' : 'Disallow: /';
49        $lines[] = '';
50        if ($indexable && settings('seo.sitemap_enabled', true)) {
51            $lines[] = 'Sitemap: ' . url('/sitemap.xml');
52        }
53
54        return response(implode("\n", $lines), 200, ['Content-Type' => 'text/plain']);
55    }
56}