Back to Snippets
LaravelPHP

Laravel API Resource

Transform Eloquent models into structured JSON API responses.

laravelapiresourcejson
<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray(Request 400">$request): array
    {
        return [
            class=class="text-emerald-400">"text-emerald-400">'id' => 400">$this->id,
            class=class="text-emerald-400">"text-emerald-400">'title' => 400">$this->title,
            class=class="text-emerald-400">"text-emerald-400">'slug' => 400">$this->slug,
            class=class="text-emerald-400">"text-emerald-400">'excerpt' => str(400">$this->content)->limit(120),
            class=class="text-emerald-400">"text-emerald-400">'content' => 400">$this->when(400">$request->routeIs(class=class="text-emerald-400">"text-emerald-400">'posts.show'), 400">$this->content),
            class=class="text-emerald-400">"text-emerald-400">'author' => new UserResource(400">$this->whenLoaded(class=class="text-emerald-400">"text-emerald-400">'author')),
            class=class="text-emerald-400">"text-emerald-400">'tags' => TagResource::collection(400">$this->whenLoaded(class=class="text-emerald-400">"text-emerald-400">'tags')),
            class=class="text-emerald-400">"text-emerald-400">'published_at' => 400">$this->published_at?->toISOString(),
            class=class="text-emerald-400">"text-emerald-400">'created_at' => 400">$this->created_at->toISOString(),
        ];
    }
}

class=class="text-emerald-400">"text-gray">// Controller usage:
class=class="text-emerald-400">"text-gray">// return PostResource::collection(Post::with(class=class="text-emerald-400">"text-emerald-400">'author', class=class="text-emerald-400">"text-emerald-400">'tags')->paginate(15));

How to Use

Create with: php artisan make:resource PostResource. Return from controllers: return new PostResource($post) for single items, or PostResource::collection($posts) for lists. Use whenLoaded() to conditionally include relations.

Related Technology

Laravel

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call