Laravel

Laravel API Resources: Transform Your Data

December 24, 2025 1 min read 30 views

Transform data with API resources:

Create Resource

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

Resource Collections

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

Conditional Attributes

return [
    'id' => $this->id,
    'secret' => $this->when($request->user()->isAdmin(), 'secret-value'),
];
Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!