feat: refactor product detail retrieval to simplify variant handling and enhance response structure

This commit is contained in:
2026-07-01 01:05:21 +00:00
parent 429fa36b05
commit 1aa831f921
5 changed files with 98 additions and 90 deletions

View File

@@ -2,11 +2,12 @@
namespace App\Domains\Catalog\Resources;
use App\Domains\Catalog\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin \App\Domains\Catalog\Models\Product
* @mixin Product
*/
class ProductResource extends JsonResource
{
@@ -23,15 +24,26 @@ class ProductResource extends JsonResource
'nombre' => $this->nombre,
'descripcion' => $this->descripcion,
'precio' => $this->precio,
'category' => $this->whenLoaded('category', fn () => $this->category?->nombre),
'category' => $this->whenLoaded('category', fn () => $this->category?->nombre),
'brand' => $this->whenLoaded('brand', fn () => $this->brand?->nombre),
'images' => $this->whenLoaded('attachments', fn () =>
$this->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values()
'images' => $this->whenLoaded('attachments', fn () => $this->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values()
),
'attributes' => AttributeResource::collection($this->whenLoaded('attributes')),
'variants' => ProductVariantResource::collection($this->whenLoaded('variants')),
'variants_map' => $this->whenLoaded('variants', fn () => $this->variants
->map(fn ($variant) => [
'variant_id' => $variant->id,
'stock' => $variant->stock,
'attributes' => $variant->definitions
->mapWithKeys(fn ($definition) => [
$definition->productAttribute?->attribute?->codigo => $definition->value,
])
->filter(fn ($value, $key) => $key !== null)
->toArray(),
])
->values()
),
'variant' => $this->when(
$this->getSelectedVariant() !== null,
fn () => ProductVariantResource::make($this->getSelectedVariant())