Files
landing-api/app/Http/Controllers/Api/PublicApi/V1/PageController.php
Josep Piguillem 9f970808ca
Some checks failed
Tests / lint (push) Has been cancelled
Tests / test (push) Has been cancelled
Tests / test-postgres (push) Has been cancelled
Tests / mcp (push) Has been cancelled
Tag blog posts and sign them with a member
Tags are named in every language and made from the page form; the byline is
the member who signs a post on the site. The public API sends both, filters
posts by tag and lists the tags in use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:01:18 +02:00

74 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\PublicApi\V1;
use App\Http\Resources\PublicApi\PublicPageResource;
use App\Models\Page;
use App\Models\Tag;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class PageController extends PublicController
{
public function index(Request $request): AnonymousResourceCollection
{
$pages = Page::query()
->with(['category', 'featuredMedia', 'tags', 'byline.avatarMedia'])
->unless($this->isPreview($request), fn (Builder $q) => $q->published())
->when($request->filled('category'), fn (Builder $q) => $q
->whereHas('category', fn (Builder $c) => $c
->where('slug->'.app()->getLocale(), $request->string('category'))))
->when($request->boolean('featured'), fn (Builder $q) => $q->where('is_featured', true))
->when($request->filled('tag'), fn (Builder $q) => $q
->whereHas('tags', fn (Builder $t) => $t
->where('slug->'.app()->getLocale(), $request->string('tag'))))
->orderByDesc('published_at')
->paginate($this->perPage($request))
->withQueryString();
return PublicPageResource::collection($pages);
}
public function show(Request $request, string $slug): PublicPageResource
{
$page = Page::query()
->with(['category', 'featuredMedia', 'tags', 'byline.avatarMedia'])
->whereSlug($slug)
->unless($this->isPreview($request), fn (Builder $q) => $q->published())
->firstOrFail();
return PublicPageResource::make($page);
}
/**
* The tags used by something published, with how many posts each has in
* the request's language — for a blog to offer them as a way in.
*/
public function tags(Request $request): JsonResponse
{
$locale = app()->getLocale();
$published = fn (Builder $q) => $q
->unless($this->isPreview($request), fn (Builder $q) => $q->published())
->whereNotNull("slug->{$locale}");
$tags = Tag::query()
->whereHas('pages', $published)
->withCount(['pages' => $published])
->get()
->filter(fn (Tag $tag) => filled($tag->getTranslation('slug', $locale, false)))
->sortByDesc('pages_count')
->map(fn (Tag $tag) => [
'name' => $tag->getTranslation('name', $locale),
'slug' => $tag->getTranslation('slug', $locale, false),
'count' => (int) $tag->pages_count,
])
->values();
return response()->json(['data' => $tags]);
}
}