Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Laravel

Laravel API Resources: Transform Your Data

Use Laravel API resources to consistently format your API responses.

24 December 20251 min readLaravelاقرأ بالعربية

On this page

  1. Create Resource
  2. Resource Collections
  3. Conditional Attributes

Transform data with API resources:

Create Resource

php
class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'author' => new AuthorResource($this->author),
        ];
    }
}

Resource Collections

php
return PostResource::collection(Post::all());

Conditional Attributes

php
return [
    'id' => $this->id,
    'secret' => $this->when($request->user()->isAdmin(), 'secret-value'),
];
All articles

Keep reading

  • Laravel Action Classes Pattern16 January 20261 min read
  • Laravel Action Classes: Single Responsibility16 January 20261 min read
  • Laravel API Rate Limiting16 January 20261 min read