Files
parsaaghayi-backend/app/Http/Controllers/Api/Admin/AdminResourceController.php
T
Parsa Aghayi 5ae1d1a632 Eager-load relations the admin read API returns
Edit forms are populated from a single request, so posts need their tags and
projects their category attached; otherwise the tag multi-select and category
picker come back empty.
2026-10-01 16:00:06 -04:00

78 lines
2.6 KiB
PHP

<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\Blog\Category;
use App\Models\Blog\Post;
use App\Models\Blog\Tag;
use App\Models\Website\AboutMe;
use App\Models\Website\Project;
use App\Models\Website\ProjectCategory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class AdminResourceController extends Controller
{
/**
* Resources the admin panel may read and manage.
*
* @var array<string, class-string>
*/
private const RESOURCES = [
'posts' => Post::class,
'categories' => Category::class,
'tags' => Tag::class,
'projects' => Project::class,
'project-categories' => ProjectCategory::class,
'about-me' => AboutMe::class,
];
/**
* Relations eager loaded per resource, so an editing form is populated
* from a single request instead of a fan-out of lookups.
*
* @var array<string, array<int, string>>
*/
private const RELATIONS = [
'posts' => ['tags'],
'projects' => ['category'],
];
/**
* Raw rows for content management.
*
* The public API intentionally returns display-oriented payloads: single
* translated values, reshaped image arrays, no internal ids for some
* fields. An editing form needs the stored row instead, including both
* locales, so this endpoint serialises the model as-is.
*/
public function index(Request $request, string $resource): JsonResponse
{
$model = self::RESOURCES[$resource] ?? null;
if ($model === null) {
return response()->json(['message' => 'Unknown admin resource.'], 404);
}
$rows = $model::query()->with(self::RELATIONS[$resource] ?? [])->orderByDesc('id')->get();
return response()->json(['data' => $rows]);
}
/**
* Field names accepted per resource, so the admin panel and the write
* endpoints cannot drift apart silently.
*/
public static function writableFields(string $resource): array
{
return match ($resource) {
'posts' => ['title', 'body', 'excerpt', 'slug', 'author_id', 'category_id', 'featured_image', 'views', 'likes', 'published_at', 'tags'],
'categories' => ['name', 'slug', 'description', 'short_description', 'image'],
'tags' => ['name', 'slug'],
'projects' => ['category_id', 'image1', 'image2', 'title_fa', 'title_en', 'description_fa', 'description_en'],
'about-me' => ['image', 'title_fa', 'title_en', 'description_fa', 'description_en'],
default => [],
};
}
}