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, '.', ''),
int) $this->stock,
$this->created_at ? $this->created_at->toDateTimeString() : null,
$this->updated_at ? $this->updated_at->toDateTimeString() : null,
];
}
public function with(Request $request): array
{
return [
'status_code' => 200,
'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