مقاله

JsonResource، collection، whenLoaded، conditional fields و Pagination wrapper — خروجی API یکدست و امن.

API Resource در Laravel — تبدیل Model به JSON حرفه‌ای

API Resource در Laravel — تبدیل Model به JSON حرفه‌ای

برگرداندن $post->toArray() از API یعنی leak کردن فیلدهای داخلی، relationهای N+1 و format ناهمگون. API Resource (JsonResource) لایه transformation رسمی Laravel است — در ساخت REST API بدون آن نیمه‌کاره می‌ماند.

ساخت Resource

php artisan make:resource PostResource
class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'excerpt' => $this->excerpt,
            'published_at' => $this->published_at?->toIso8601String(),
            'category' => CategoryResource::make($this->whenLoaded('category')),
            'author' => new UserResource($this->whenLoaded('user')),
            'can' => [
                'update' => $request->user()?->can('update', $this->resource),
            ],
        ];
    }
}

whenLoaded — کلید رفع N+1 در JSON

اگر relation لود نشده، key در JSON نمی‌آید — از accidental lazy load جلوگیری می‌کند. همیشه در controller with() بزنید — Eager Loading.

Collection

return PostResource::collection($posts);

// یا pagination
return PostResource::collection($posts)->response();

Laravel meta pagination را خودکار wrap می‌کند:

{
  "data": [...],
  "links": { "next": "..." },
  "meta": { "current_page": 1 }
}

فیلدهای شرطی

'email' => $this->when($request->user()?->is_admin, $this->user->email),
'secret' => $this->whenAppended('secret'),

Resource تو در تو

CategoryResource جدا — DRY و control روی فیلدهای هر entity.

withoutWrapping

// AppServiceProvider
JsonResource::withoutWrapping(); // حذف data wrapper برای collection ساده

یکدست در کل API تصمیم بگیرید.

merge و additional

return (new PostResource($post))->additional([
    'meta' => ['version' => '1.0'],
]);

اشتباهات

  • برگرداندن model خام
  • logic سنگین در toArray
  • فراموش whenLoaded → N+1
  • format تاریخ inconsistent

جمع‌بندی

هر public API endpoint → Resource. خطاها: Error handling. فیلتر: Pagination.

طراحی API