ProductResource.php
app/Http/Resources/ProductResource.php
API Resource for Product
The ProductResource transforms product model data for API responses, ensuring consistent structure and type casting.
• Consistent float/integer casting
• Relationship and computed property support
• Custom response metadata
Complete Implementation
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class ProductResource extends JsonResource { public function toArray(Request $request): array { return [ 'id' => $this->id, 'name' => $this->name, $this->description, float) number_format($this->price, 2, '.', ''), // Ensure consistent float format int) $this->stock, // Ensure integer type $this->created_at ? $this->created_at->toDateTimeString() : null, // ISO 8601 format $this->updated_at ? $this->updated_at->toDateTimeString() : null, // Example of conditional loading for relationships (if Product had them) // 'category' => new CategoryResource($this->whenLoaded('category')) // 'tags' => TagResource::collection($this->whenLoaded('tags')) // Example of a computed property not directly from the database // 'is_available' => $this->stock > 0, ]; } public function with(Request $request): array { return [ 'status_code' => 200, // Example: add a specific status code for this resource's data 'custom_message' => 'Product data successfully retrieved.', ]; } }
💡
Key Features
• Consistent type casting for API consumers
• Easily extendable for relationships and computed fields
• Custom metadata in API responses