1. APIリソース
php artisan make:resource ProductResource
php artisan make:resource ProductCollection --collection
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'slug' => $this->slug,
'price' => $this->price,
'formatted_price' => number_format($this->price) . 'đ',
'category' => new CategoryResource($this->whenLoaded('category')),
'tags' => TagResource::collection($this->whenLoaded('tags')),
'review_count' => $this->whenCounted('reviews'),
'avg_rating' => $this->when($this->avg_rating !== null, $this->avg_rating),
'created_at' => $this->created_at->toISOString(),
];
}
}
2. リソースの収集
class ProductCollection extends ResourceCollection
{
public function toArray($request): array
{
return [
'data' => $this->collection,
'meta' => [
'total' => $this->total(),
'per_page' => $this->perPage(),
],
];
}
}
// Controller
public function index()
{
$products = Product::with('category')
->withCount('reviews')
->paginate(20);
return new ProductCollection($products);
}
public function show(Product $product)
{
$product->load(['category', 'tags', 'reviews.user']);
return new ProductResource($product);
}
3. JSON 応答
// Success
return response()->json(['message' => 'Created'], 201);
// Error
return response()->json(['error' => 'Not Found'], 404);
// Custom response macro
// AppServiceProvider
Response::macro('success', function ($data = null, $message = 'OK', $code = 200) {
return response()->json([
'success' => true,
'message' => $message,
'data' => $data,
], $code);
});
return response()->success($product, 'Product created', 201);
4. API のバージョン管理
// routes/api.php
Route::prefix('v1')->group(function () {
Route::apiResource('products', V1\ProductController::class);
});
Route::prefix('v2')->group(function () {
Route::apiResource('products', V2\ProductController::class);
});
次の記事: ファイルストレージとメディア。