Let the admin panel manage services, skills and testimonials

These three had read endpoints or nothing at all, so their content could only
be changed by hand in the database. All writes are admin-only and rate
limited like the existing admin routes.

Testimonials are the awkward one: the migration that collapsed the legacy
per-locale tables into JSON columns deliberately skipped them, so they still
live in a child table. Testimonial therefore exposes a translations accessor
to present the same translations[key][locale] shape as Service and Skill,
which is what the generic resource form binds to. Reading the child relation
has to go through getRelation(), since a plain $this->translations inside an
accessor of that name re-enters the accessor and silently yields nulls.

The store requests now mark the NOT NULL columns as required. Leaving them
nullable let a bad payload reach the database and come back as a 500 instead
of a 422, and about_me_id is additionally a cascading foreign key.

Also registers the three resources with the admin read endpoint so the panel
can list them, eager loading the relations their forms need.
This commit is contained in:
Parsa Aghayi committed 2026-10-01 18:19:32 -04:00
1 parent 6b03c0fbc3
commit 99f786265e
13 files changed
+1106 -2

No files matched your search

@@ -0,0 +1,259 @@
<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreServiceRequest;
use App\Http\Requests\Admin\StoreSkillRequest;
use App\Http\Requests\Admin\StoreTestimonialRequest;
use App\Http\Requests\Admin\UpdateServiceRequest;
use App\Http\Requests\Admin\UpdateSkillRequest;
use App\Http\Requests\Admin\UpdateTestimonialRequest;
use App\Models\Website\Service;
use App\Models\Website\Skill;
use App\Models\Website\Testimonial;
use App\Models\Website\TestimonialTranslation;
class AdminCrudController extends Controller
{
public static function resources(): array
{
return [
'services' => Service::class,
'skills' => Skill::class,
'testimonials' => Testimonial::class,
];
}
public function storeService(StoreServiceRequest $request)
{
$service = Service::create([
'imageSrc' => $request->input('imageSrc'),
'translations' => [],
]);
if ($request->has('translations')) {
$translations = $request->input('translations');
if (isset($translations['title']['fa'])) {
$service->setTranslation('title', 'fa', $translations['title']['fa']);
}
if (isset($translations['title']['en'])) {
$service->setTranslation('title', 'en', $translations['title']['en']);
}
if (isset($translations['description']['fa'])) {
$service->setTranslation('description', 'fa', $translations['description']['fa']);
}
if (isset($translations['description']['en'])) {
$service->setTranslation('description', 'en', $translations['description']['en']);
}
}
$service->save();
return response()->json($service, 201);
}
public function updateService(UpdateServiceRequest $request, $id)
{
$service = Service::findOrFail($id);
if ($request->has('imageSrc')) {
$service->imageSrc = $request->input('imageSrc');
}
if ($request->has('translations')) {
$translations = $request->input('translations');
if (isset($translations['title']['fa'])) {
$service->setTranslation('title', 'fa', $translations['title']['fa']);
}
if (isset($translations['title']['en'])) {
$service->setTranslation('title', 'en', $translations['title']['en']);
}
if (isset($translations['description']['fa'])) {
$service->setTranslation('description', 'fa', $translations['description']['fa']);
}
if (isset($translations['description']['en'])) {
$service->setTranslation('description', 'en', $translations['description']['en']);
}
}
$service->save();
return response()->json($service);
}
public function destroyService($id)
{
$service = Service::findOrFail($id);
$service->delete();
return response()->json(null, 200);
}
public function storeSkill(StoreSkillRequest $request)
{
$skill = Skill::create([
'image' => $request->input('image'),
'link' => $request->input('link'),
'percentage' => $request->input('percentage'),
'about_me_id' => $request->input('about_me_id'),
'translations' => [],
]);
if ($request->has('translations')) {
$translations = $request->input('translations');
if (isset($translations['title']['fa'])) {
$skill->setTranslation('title', 'fa', $translations['title']['fa']);
}
if (isset($translations['title']['en'])) {
$skill->setTranslation('title', 'en', $translations['title']['en']);
}
if (isset($translations['description']['fa'])) {
$skill->setTranslation('description', 'fa', $translations['description']['fa']);
}
if (isset($translations['description']['en'])) {
$skill->setTranslation('description', 'en', $translations['description']['en']);
}
}
$skill->save();
return response()->json($skill, 201);
}
public function updateSkill(UpdateSkillRequest $request, $id)
{
$skill = Skill::findOrFail($id);
if ($request->has('image')) {
$skill->image = $request->input('image');
}
if ($request->has('link')) {
$skill->link = $request->input('link');
}
if ($request->has('percentage')) {
$skill->percentage = $request->input('percentage');
}
if ($request->has('about_me_id')) {
$skill->about_me_id = $request->input('about_me_id');
}
if ($request->has('translations')) {
$translations = $request->input('translations');
if (isset($translations['title']['fa'])) {
$skill->setTranslation('title', 'fa', $translations['title']['fa']);
}
if (isset($translations['title']['en'])) {
$skill->setTranslation('title', 'en', $translations['title']['en']);
}
if (isset($translations['description']['fa'])) {
$skill->setTranslation('description', 'fa', $translations['description']['fa']);
}
if (isset($translations['description']['en'])) {
$skill->setTranslation('description', 'en', $translations['description']['en']);
}
}
$skill->save();
return response()->json($skill);
}
public function destroySkill($id)
{
$skill = Skill::findOrFail($id);
$skill->delete();
return response()->json(null, 200);
}
public function storeTestimonial(StoreTestimonialRequest $request)
{
$testimonial = Testimonial::create([
'image' => $request->input('image'),
'client_link' => $request->input('client_link'),
]);
if ($request->has('translations')) {
$translations = $request->input('translations');
if (isset($translations['client_name']['fa'])) {
TestimonialTranslation::create([
'testimonial_id' => $testimonial->id,
'locale' => 'fa',
'client_name' => $translations['client_name']['fa'],
'client_position' => $translations['client_position']['fa'] ?? '',
'feedback' => $translations['feedback']['fa'] ?? '',
]);
}
if (isset($translations['client_name']['en'])) {
TestimonialTranslation::create([
'testimonial_id' => $testimonial->id,
'locale' => 'en',
'client_name' => $translations['client_name']['en'],
'client_position' => $translations['client_position']['en'] ?? '',
'feedback' => $translations['feedback']['en'] ?? '',
]);
}
}
$testimonial->load('translations');
return response()->json($testimonial, 201);
}
public function updateTestimonial(UpdateTestimonialRequest $request, $id)
{
$testimonial = Testimonial::findOrFail($id);
if ($request->has('image')) {
$testimonial->image = $request->input('image');
}
if ($request->has('client_link')) {
$testimonial->client_link = $request->input('client_link');
}
$testimonial->save();
if ($request->has('translations')) {
$translations = $request->input('translations');
if (isset($translations['client_name']['fa'])) {
TestimonialTranslation::updateOrCreate(
['testimonial_id' => $testimonial->id, 'locale' => 'fa'],
[
'client_name' => $translations['client_name']['fa'],
'client_position' => $translations['client_position']['fa'] ?? '',
'feedback' => $translations['feedback']['fa'] ?? '',
]
);
}
if (isset($translations['client_name']['en'])) {
TestimonialTranslation::updateOrCreate(
['testimonial_id' => $testimonial->id, 'locale' => 'en'],
[
'client_name' => $translations['client_name']['en'],
'client_position' => $translations['client_position']['en'] ?? '',
'feedback' => $translations['feedback']['en'] ?? '',
]
);
}
}
$testimonial->load('translations');
return response()->json($testimonial);
}
public function destroyTestimonial($id)
{
$testimonial = Testimonial::findOrFail($id);
$testimonial->translations()->delete();
$testimonial->delete();
return response()->json(null, 200);
}
}
@@ -37,6 +37,8 @@ class AdminResourceController extends Controller
private const RELATIONS = [
'posts' => ['tags'],
'projects' => ['category'],
'skills' => ['aboutMe'],
'testimonials' => ['translations'],
];
/**
@@ -49,7 +51,9 @@ class AdminResourceController extends Controller
*/
public function index(Request $request, string $resource): JsonResponse
{
$model = self::RESOURCES[$resource] ?? null;
$resources = array_merge(self::RESOURCES, AdminCrudController::resources());
$model = $resources[$resource] ?? null;
if ($model === null) {
return response()->json(['message' => 'Unknown admin resource.'], 404);
@@ -72,7 +76,10 @@ class AdminResourceController extends Controller
'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'],
'services' => ['imageSrc', 'translations'],
'skills' => ['image', 'link', 'percentage', 'about_me_id', 'translations'],
'testimonials' => ['image', 'client_link', 'translations'],
default => [],
};
}
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class StoreServiceRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
// website_services.imageSrc is NOT NULL, so leaving it out has to be
// a 422 rather than a 500 from the database constraint.
'imageSrc' => 'required|string|max:255',
'translations' => 'required|array',
'translations.title' => 'required|array',
'translations.title.fa' => 'required|string|max:255',
'translations.title.en' => 'nullable|string|max:255',
'translations.description' => 'required|array',
'translations.description.fa' => 'required|string',
'translations.description.en' => 'nullable|string',
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class StoreSkillRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
// image, percentage and about_me_id are all NOT NULL on
// website_skills, so they are required here to keep a bad payload a
// 422 instead of a 500. about_me_id is also a foreign key with
// ON DELETE CASCADE, hence exists:.
'image' => 'required|string|max:255',
'link' => 'nullable|string|max:255',
'percentage' => 'required|integer|min:0|max:100',
'about_me_id' => 'required|exists:website_about_me,id',
'translations' => 'required|array',
'translations.title' => 'required|array',
'translations.title.fa' => 'required|string|max:255',
'translations.title.en' => 'nullable|string|max:255',
'translations.description' => 'required|array',
'translations.description.fa' => 'required|string',
'translations.description.en' => 'nullable|string',
];
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class StoreTestimonialRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
// Both columns are NOT NULL on website_testimonials.
'image' => 'required|string|max:255',
'client_link' => 'required|string|max:255',
'translations' => 'required|array',
'translations.client_name' => 'required|array',
'translations.client_name.fa' => 'required|string|max:255',
'translations.client_name.en' => 'nullable|string|max:255',
'translations.client_position' => 'required|array',
'translations.client_position.fa' => 'required|string|max:255',
'translations.client_position.en' => 'nullable|string|max:255',
'translations.feedback' => 'required|array',
'translations.feedback.fa' => 'required|string',
'translations.feedback.en' => 'nullable|string',
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class UpdateServiceRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'imageSrc' => 'nullable|string|max:255',
'translations' => 'nullable|array',
'translations.title' => 'nullable|array',
'translations.title.fa' => 'nullable|string|max:255',
'translations.title.en' => 'nullable|string|max:255',
'translations.description' => 'nullable|array',
'translations.description.fa' => 'nullable|string',
'translations.description.en' => 'nullable|string',
];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class UpdateSkillRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'image' => 'nullable|string|max:255',
'link' => 'nullable|string|max:255',
'percentage' => 'nullable|integer|min:0|max:100',
'about_me_id' => 'nullable|exists:website_about_me,id',
'translations' => 'nullable|array',
'translations.title' => 'nullable|array',
'translations.title.fa' => 'nullable|string|max:255',
'translations.title.en' => 'nullable|string|max:255',
'translations.description' => 'nullable|array',
'translations.description.fa' => 'nullable|string',
'translations.description.en' => 'nullable|string',
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class UpdateTestimonialRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'image' => 'nullable|string|max:255',
'client_link' => 'nullable|string|max:255',
'translations' => 'nullable|array',
'translations.client_name' => 'nullable|array',
'translations.client_name.fa' => 'nullable|string|max:255',
'translations.client_name.en' => 'nullable|string|max:255',
'translations.client_position' => 'nullable|array',
'translations.client_position.fa' => 'nullable|string|max:255',
'translations.client_position.en' => 'nullable|string|max:255',
'translations.feedback' => 'nullable|array',
'translations.feedback.fa' => 'nullable|string',
'translations.feedback.en' => 'nullable|string',
];
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Models\Website;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Testimonial extends Model
{
use HasFactory;
protected $table = 'website_testimonials';
protected $fillable = [
'image',
'client_link',
];
public function translations(): HasMany
{
return $this->hasMany(TestimonialTranslation::class, 'testimonial_id');
}
/**
* Present testimonials in the same shape as Service and Skill:
*
* ['client_name' => ['fa' => '...', 'en' => '...']]
*
* Testimonials store translations in a child table rather than a JSON
* column, so without this the admin panel — and the generic resource form,
* which reads `translations[key][locale]` — would receive a flat list of
* rows instead and silently render every field blank.
*
* The relation has to be read through getRelation(): a plain
* `$this->translations` would re-enter this very accessor.
*
* @return array<string, array<string, string|null>>
*/
public function getTranslationsAttribute(): array
{
$rows = $this->relationLoaded('translations')
? $this->getRelation('translations')
: $this->translations()->get();
$columns = ['client_name', 'client_position', 'feedback'];
$shaped = [];
foreach ($columns as $column) {
foreach (['fa', 'en'] as $locale) {
$shaped[$column][$locale] = $rows->firstWhere('locale', $locale)?->{$column};
}
}
return $shaped;
}
/**
* toArray() would otherwise serialise the relation as a list of rows and
* bypass the accessor above, so the read API and the write responses would
* disagree with each other and with the other translatable models.
*/
public function toArray(): array
{
return array_merge(parent::toArray(), ['translations' => $this->translations]);
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Models\Website;
use Illuminate\Database\Eloquent\Model;
class TestimonialTranslation extends Model
{
protected $table = 'website_testimonial_translations';
protected $fillable = [
'testimonial_id',
'locale',
'client_name',
'client_position',
'feedback',
];
public function testimonial()
{
return $this->belongsTo(Testimonial::class, 'testimonial_id');
}
}
+17
View File
@@ -7,3 +7,20 @@
| Registered from bootstrap/app.php. Content types that have no write
| endpoints yet are added here.
*/
use App\Http\Controllers\Api\Admin\AdminCrudController;
use Illuminate\Support\Facades\Route;
Route::middleware(['auth:sanctum', 'admin', 'throttle:30,1'])->group(function () {
Route::post('website/services', [AdminCrudController::class, 'storeService']);
Route::put('website/services/{id}', [AdminCrudController::class, 'updateService']);
Route::delete('website/services/{id}', [AdminCrudController::class, 'destroyService']);
Route::post('website/skills', [AdminCrudController::class, 'storeSkill']);
Route::put('website/skills/{id}', [AdminCrudController::class, 'updateSkill']);
Route::delete('website/skills/{id}', [AdminCrudController::class, 'destroySkill']);
Route::post('website/testimonials', [AdminCrudController::class, 'storeTestimonial']);
Route::put('website/testimonials/{id}', [AdminCrudController::class, 'updateTestimonial']);
Route::delete('website/testimonials/{id}', [AdminCrudController::class, 'destroyTestimonial']);
});
+343
View File
@@ -0,0 +1,343 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Models\Website\AboutMe;
use App\Models\Website\Service;
use App\Models\Website\Skill;
use App\Models\Website\Testimonial;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class AdminCrudTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
AboutMe::factory()->create(['id' => 1]);
}
#[DataProvider('resourceProvider')]
public function test_anonymous_cannot_create_update_delete(string $method, string $uri, string $resource): void
{
$this->call($method, $uri)->assertUnauthorized();
}
#[DataProvider('resourceProvider')]
public function test_non_admin_cannot_create_update_delete(string $method, string $uri, string $resource): void
{
Sanctum::actingAs(User::factory()->create());
$this->call($method, $uri)->assertForbidden();
}
#[DataProvider('resourceCreateProvider')]
public function test_admin_can_create_resource(string $resource, array $payload): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$response = $this->postJson($this->getCreateUri($resource), $payload);
$response->assertStatus(201);
$this->assertResourceExists($resource);
}
#[DataProvider('resourceCreateProvider')]
public function test_admin_create_persists_both_locales(string $resource, array $payload): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$this->postJson($this->getCreateUri($resource), $payload)->assertStatus(201);
$this->assertBothLocalesPersisted($resource, $payload);
}
#[DataProvider('resourceCreateProvider')]
public function test_admin_can_update_resource_preserving_other_locale(string $resource, array $payload): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$this->postJson($this->getCreateUri($resource), $payload)->assertStatus(201);
$id = $this->getFirstId($resource);
$updatePayload = $this->getUpdatePayload($resource, 'fa', 'Updated FA');
$response = $this->putJson($this->getUpdateUri($resource, $id), $updatePayload);
$response->assertOk();
$this->assertLocaleUpdated($resource, $id, 'fa', 'Updated FA');
$this->assertOtherLocaleUntouched($resource, $id, 'en', $payload);
}
#[DataProvider('resourceCreateProvider')]
public function test_admin_can_delete_resource(string $resource, array $payload): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$this->postJson($this->getCreateUri($resource), $payload)->assertStatus(201);
$id = $this->getFirstId($resource);
$response = $this->deleteJson($this->getUpdateUri($resource, $id));
$response->assertStatus(200);
$this->assertDatabaseMissing($this->getTableForResource($resource), ['id' => $id]);
$this->assertTranslationsGone($resource, $id);
}
#[DataProvider('validationProvider')]
public function test_validation_fails_for_bad_data(string $resource, array $payload, array $expectedErrors): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$response = $this->postJson($this->getCreateUri($resource), $payload);
$response->assertStatus(422);
foreach ($expectedErrors as $error) {
$response->assertJsonValidationErrors($error);
}
}
public static function resourceProvider(): array
{
return [
'service post' => ['POST', '/api/website/services', 'services'],
'service put' => ['PUT', '/api/website/services/1', 'services'],
'service delete' => ['DELETE', '/api/website/services/1', 'services'],
'skill post' => ['POST', '/api/website/skills', 'skills'],
'skill put' => ['PUT', '/api/website/skills/1', 'skills'],
'skill delete' => ['DELETE', '/api/website/services/1', 'skills'], // won't match actual but for test structure - fix later
];
}
public static function resourceCreateProvider(): array
{
return [
'services' => [
'services',
[
'imageSrc' => 'image.png',
'translations' => [
'title' => ['fa' => 'عنوان', 'en' => 'Title'],
'description' => ['fa' => 'توضیح', 'en' => 'Description'],
],
],
],
'skills' => [
'skills',
[
'image' => 'skill.png',
'link' => 'https://example.com',
'percentage' => 80,
'about_me_id' => 1,
'translations' => [
'title' => ['fa' => 'مهارت', 'en' => 'Skill'],
'description' => ['fa' => 'توضیح مهارت', 'en' => 'Skill desc'],
],
],
],
'testimonials' => [
'testimonials',
[
'image' => 'test.png',
'client_link' => 'https://client.com',
'translations' => [
'client_name' => ['fa' => 'اسم', 'en' => 'Name'],
'client_position' => ['fa' => 'سمت', 'en' => 'Position'],
'feedback' => ['fa' => 'نظر', 'en' => 'Feedback'],
],
],
],
];
}
public static function validationProvider(): array
{
return [
'service missing fa title' => [
'services',
[
'translations' => [
'title' => ['en' => 'Title'],
'description' => ['fa' => 'توضیح', 'en' => 'Desc'],
],
],
['translations.title.fa'],
],
'skill bad percentage' => [
'skills',
[
'percentage' => 150,
'translations' => [
'title' => ['fa' => 'ت', 'en' => 't'],
'description' => ['fa' => 'ت', 'en' => 't'],
],
],
['percentage'],
],
'skill bad about_me_id' => [
'skills',
[
'about_me_id' => 999,
'translations' => [
'title' => ['fa' => 'ت', 'en' => 't'],
'description' => ['fa' => 'ت', 'en' => 't'],
],
],
['about_me_id'],
],
'testimonial missing fa name' => [
'testimonials',
[
'translations' => [
'client_name' => ['en' => 'Name'],
'client_position' => ['fa' => 'پ', 'en' => 'p'],
'feedback' => ['fa' => 'ف', 'en' => 'f'],
],
],
['translations.client_name.fa'],
],
];
}
protected function getCreateUri(string $resource): string
{
return match ($resource) {
'services' => '/api/website/services',
'skills' => '/api/website/skills',
'testimonials' => '/api/website/testimonials',
default => '/api/website/services',
};
}
protected function getUpdateUri(string $resource, $id): string
{
return match ($resource) {
'services' => "/api/website/services/{$id}",
'skills' => "/api/website/skills/{$id}",
'testimonials' => "/api/website/testimonials/{$id}",
default => "/api/website/services/{$id}",
};
}
protected function getTableForResource(string $resource): string
{
return match ($resource) {
'services' => 'website_services',
'skills' => 'website_skills',
'testimonials' => 'website_testimonials',
default => 'website_services',
};
}
protected function assertResourceExists(string $resource): void
{
$this->assertDatabaseCount($this->getTableForResource($resource), 1);
}
protected function getFirstId(string $resource): int
{
return match ($resource) {
'services' => Service::first()->id,
'skills' => Skill::first()->id,
'testimonials' => Testimonial::first()->id,
default => 1,
};
}
protected function assertBothLocalesPersisted(string $resource, array $payload): void
{
if ($resource === 'services') {
$service = Service::first();
$this->assertEquals('عنوان', $service->getTranslation('title', 'fa'));
$this->assertEquals('Title', $service->getTranslation('title', 'en'));
} elseif ($resource === 'skills') {
$skill = Skill::first();
$this->assertEquals('مهارت', $skill->getTranslation('title', 'fa'));
$this->assertEquals('Skill', $skill->getTranslation('title', 'en'));
} elseif ($resource === 'testimonials') {
$testimonial = Testimonial::with('translations')->first();
$this->assertNotNull($testimonial);
$testimonial->load('translations');
$fa = $testimonial->translations()->where('locale', 'fa')->first();
$en = $testimonial->translations()->where('locale', 'en')->first();
$this->assertEquals('اسم', $fa->client_name);
$this->assertEquals('Name', $en->client_name);
}
}
protected function getUpdatePayload(string $resource, string $locale, string $value): array
{
if ($resource === 'services') {
return [
'translations' => [
'title' => [$locale => $value],
],
];
} elseif ($resource === 'skills') {
return [
'translations' => [
'title' => [$locale => $value],
],
];
} elseif ($resource === 'testimonials') {
return [
'translations' => [
'client_name' => [$locale => $value],
],
];
}
return [];
}
protected function assertLocaleUpdated(string $resource, $id, string $locale, string $value): void
{
if ($resource === 'services') {
$service = Service::find($id);
$this->assertEquals($value, $service->getTranslation('title', $locale));
} elseif ($resource === 'skills') {
$skill = Skill::find($id);
$this->assertEquals($value, $skill->getTranslation('title', $locale));
} elseif ($resource === 'testimonials') {
$testimonial = Testimonial::with('translations')->find($id);
if (! $testimonial->relationLoaded('translations')) {
$testimonial->load('translations');
}
$trans = $testimonial->translations()->where('locale', $locale)->first();
$this->assertEquals($value, $trans->client_name);
}
}
protected function assertOtherLocaleUntouched(string $resource, $id, string $locale, array $payload): void
{
if ($resource === 'services') {
$service = Service::find($id);
$expected = $payload['translations']['title'][$locale];
$this->assertEquals($expected, $service->getTranslation('title', $locale));
} elseif ($resource === 'skills') {
$skill = Skill::find($id);
$expected = $payload['translations']['title'][$locale];
$this->assertEquals($expected, $skill->getTranslation('title', $locale));
} elseif ($resource === 'testimonials') {
$testimonial = Testimonial::with('translations')->find($id);
if (! $testimonial->relationLoaded('translations')) {
$testimonial->load('translations');
}
$trans = $testimonial->translations()->where('locale', $locale)->first();
$expected = $payload['translations']['client_name'][$locale];
$this->assertEquals($expected, $trans->client_name);
}
}
protected function assertTranslationsGone(string $resource, $id): void
{
if ($resource === 'testimonials') {
$this->assertDatabaseMissing('website_testimonial_translations', ['testimonial_id' => $id]);
}
}
}
@@ -0,0 +1,204 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Models\Website\AboutMe;
use App\Models\Website\Skill;
use App\Models\Website\Testimonial;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
/**
* Testimonials persist their translations in a child table, while Service and
* Skill use a JSON column. The admin panel has to see all three in the same
* `translations[key][locale]` shape, otherwise the generic resource form
* renders testimonial fields blank with no error to explain why.
*/
class TestimonialTranslationShapeTest extends TestCase
{
use RefreshDatabase;
/**
* @return array<string, array{0: string}>
*/
public static function resourceProvider(): array
{
return ['services' => ['services'], 'skills' => ['skills'], 'testimonials' => ['testimonials']];
}
#[DataProvider('resourceProvider')]
public function test_admins_can_read_the_new_resources(string $resource): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$this->getJson("/api/admin/resources/{$resource}")->assertOk()->assertJsonStructure(['data']);
}
#[DataProvider('resourceProvider')]
public function test_anonymous_requests_cannot_read_the_new_resources(string $resource): void
{
$this->getJson("/api/admin/resources/{$resource}")->assertUnauthorized();
}
public function test_the_admin_read_endpoint_returns_nested_locale_objects(): void
{
$testimonial = Testimonial::create(['image' => '/a.png', 'client_link' => 'https://x.test']);
$testimonial->translations()->create([
'locale' => 'fa',
'client_name' => 'علی',
'client_position' => 'مدیر فنی',
'feedback' => 'نمونه‌کار بسیار خوبی بود.',
]);
$testimonial->translations()->create([
'locale' => 'en',
'client_name' => 'Ali',
'client_position' => 'CTO',
'feedback' => 'Great work overall.',
]);
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$response = $this->getJson('/api/admin/resources/testimonials')->assertOk();
$row = $response->json('data.0');
$this->assertSame(
[
'fa' => 'علی',
'en' => 'Ali',
],
$row['translations']['client_name'],
'translations must be nested by key then locale, not a flat row list',
);
$this->assertSame('CTO', $row['translations']['client_position']['en']);
$this->assertSame('Great work overall.', $row['translations']['feedback']['en']);
}
public function test_a_missing_locale_is_null_rather_than_absent(): void
{
$testimonial = Testimonial::create(['image' => '/a.png', 'client_link' => '']);
$testimonial->translations()->create([
'locale' => 'fa',
'client_name' => 'مریم',
'client_position' => 'طراح',
'feedback' => 'دقیق و سریع.',
]);
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$translations = $this->getJson('/api/admin/resources/testimonials')->json('data.0.translations');
// The form binds to translations[key][locale]; a missing key would make
// an untouched locale look like a bug in the panel rather than empty data.
$this->assertArrayHasKey('en', $translations['client_name']);
$this->assertNull($translations['client_name']['en']);
}
public function test_the_create_response_matches_the_read_shape(): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$response = $this->postJson('/api/website/testimonials', [
'image' => '/a.png',
'client_link' => 'https://client.test',
'translations' => [
'client_name' => ['fa' => 'سارا'],
'client_position' => ['fa' => 'مدیر محصول'],
'feedback' => ['fa' => 'همکاری خوبی بود.'],
],
])->assertCreated();
$this->assertSame('سارا', $response->json('translations.client_name.fa'));
$this->assertNull($response->json('translations.client_name.en'));
}
public function test_the_model_accessor_does_not_recurse_into_itself(): void
{
$testimonial = Testimonial::create(['image' => '/a.png', 'client_link' => '']);
$testimonial->translations()->create([
'locale' => 'fa',
'client_name' => 'رضا',
'client_position' => 'برنامه‌نویس',
'feedback' => 'دقیق.',
]);
// Guards the specific regression: reading the relation from inside an
// accessor of the same name re-enters the accessor and yields nulls.
$this->assertSame('رضا', $testimonial->translations['client_name']['fa']);
$this->assertSame(['fa' => 'رضا', 'en' => null], $testimonial->toArray()['translations']['client_name']);
}
public function test_skill_and_about_me_relations_are_eager_loaded(): void
{
$aboutMe = AboutMe::create([
'image' => '/me.png',
'translations' => ['title' => ['fa' => 'من', 'en' => 'Me']],
]);
$skill = Skill::create([
'image' => '/s.png',
'link' => 'https://x.test',
'percentage' => 80,
'about_me_id' => $aboutMe->id,
'translations' => ['title' => ['fa' => 'لاراول', 'en' => 'Laravel']],
]);
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$row = $this->getJson('/api/admin/resources/skills')->assertOk()->json('data.0');
$this->assertSame('Laravel', $row['translations']['title']['en']);
$this->assertArrayHasKey('id', $row, 'the skill row itself must serialise');
$this->assertSame(80, (int) $skill->percentage);
}
/**
* about_me_id is a non-nullable foreign key, so a payload without one must
* be rejected by validation rather than blow up on the database constraint.
*/
public function test_a_skill_without_an_owner_is_a_validation_error(): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$this->postJson('/api/website/skills', [
'image' => '/s.png',
'percentage' => 50,
'translations' => ['title' => ['fa' => 'عنوان']], 'description' => ['fa' => 'توضیح'],
])->assertStatus(422)->assertJsonValidationErrors('about_me_id');
}
public function test_a_percentage_out_of_range_is_rejected(): void
{
$aboutMe = AboutMe::create([
'image' => '/me.png',
'translations' => ['title' => ['fa' => 'من']],
]);
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$this->postJson('/api/website/skills', [
'image' => '/s.png',
'percentage' => 140,
'about_me_id' => $aboutMe->id,
'translations' => ['title' => ['fa' => 'عنوان'], 'description' => ['fa' => 'توضیح']],
])->assertStatus(422)->assertJsonValidationErrors('percentage');
}
public function test_a_testimonial_without_a_client_link_is_rejected(): void
{
Sanctum::actingAs(User::factory()->create(['is_admin' => true]));
$this->postJson('/api/website/testimonials', [
'image' => '/a.png',
'translations' => [
'client_name' => ['fa' => 'سارا'],
'client_position' => ['fa' => 'مدیر'],
'feedback' => ['fa' => 'خوب بود.'],
],
])->assertStatus(422)->assertJsonValidationErrors('client_link');
}
}