Parçacıklara Dön
LaravelPHP

Laravel API Resource

Eloquent modellerini yapılandırılmış JSON API yanıtlarına dönüştürme.

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));

Nasıl Kullanılır

Şu komutla oluşturun: php artisan make:resource PostResource. Controller'lardan döndürün: tekil öğeler için return new PostResource($post), listeler için PostResource::collection($posts). İlişkileri koşullu olarak dahil etmek için whenLoaded() kullanın.

İlgili Teknoloji

Laravel

Aklınızda Bir Proje mi Var?

Fikrinizi nasıl hayata geçirebileceğimizi konuşalım. İlk konseptten üretime hazır ürüne kadar — yanınızdayız.

veya ücretsiz görüşme ayarlayın