GlosarioArquitectura

¿Qué es API Resource?

Los API Resources en Laravel son clases que transforman modelos Eloquent y colecciones en respuestas JSON estructuradas, controlando exactamente que datos se exponen en la API y su formato.

API Resources

Los API Resources proporcionan una capa de transformacion entre los modelos Eloquent y las respuestas JSON de tu API. Permiten controlar exactamente que datos se exponen y como se formatean.

Crear un Resource

php artisan make:resource PostResource
php artisan make:resource PostCollection
class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'excerpt' => Str::limit($this->body, 150),
            'body' => $this->when($request->routeIs('posts.show'), $this->body),
            'published' => $this->published,
            'published_at' => $this->published_at?->toISOString(),
            'author' => new UserResource($this->whenLoaded('author')),
            'tags' => TagResource::collection($this->whenLoaded('tags')),
            'comments_count' => $this->whenCounted('comments'),
            'links' => [
                'self' => route('api.posts.show', $this),
            ],
        ];
    }
}

Uso en controladores

class PostController extends Controller
{
    public function index(): AnonymousResourceCollection
    {
        $posts = Post::with('author')
            ->withCount('comments')
            ->published()
            ->latest()
            ->paginate(15);

        return PostResource::collection($posts);
    }

    public function show(Post $post): PostResource
    {
        return new PostResource($post->load(['author', 'tags', 'comments']));
    }
}

Los Resources se pueden anidar, incluir datos condicionales con when y whenLoaded, y añadir metadata adicional. La paginacion se incluye automaticamente en la respuesta JSON.