feat: optimize category and product resource queries with eager loading and response formatting improvements

This commit is contained in:
2026-06-29 14:35:20 -03:00
parent 59ed592787
commit b05a574610
4 changed files with 16 additions and 10 deletions

View File

@@ -26,7 +26,7 @@ class CategoryController extends Controller
})
->with(['parent', 'subCategories', 'tenant'])
->orderByDesc('id')
->paginateFromRequest()
->get()
)->response();
}

View File

@@ -20,7 +20,11 @@ class ProductController extends Controller
return ProductResource::collection(
Product::query()
->where('tenant_codigo', $tenant->codigo)
->with(['attachments', 'brand', 'category'])
->with([
'attachments' => fn ($query) => $query->orderBy('attachments.id')->limit(1),
'brand',
'category',
])
->latest()
->paginateFromRequest()
)->response();

View File

@@ -17,7 +17,6 @@ class AttributeResource extends JsonResource
{
return [
'id' => $this->id,
'tenant_codigo' => $this->tenant_codigo,
'codigo' => $this->codigo,
'nombre' => $this->nombre,
'is_required' => $this->is_required,

View File

@@ -2,8 +2,6 @@
namespace App\Domains\Catalog\Resources;
use App\Domains\Catalog\Resources\BrandResource;
use App\Domains\Catalog\Resources\CategoryResource;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
@@ -20,18 +18,23 @@ class ProductResource extends JsonResource
return [
'id' => $this->id,
'tenant_codigo' => $this->tenant_codigo,
'categoria_id' => $this->categoria_id,
'category_id' => $this->categoria_id,
'brand_id' => $this->brand_id,
'slug' => $this->slug,
'nombre' => $this->nombre,
'descripcion' => $this->descripcion,
'precio' => $this->precio,
'category' => CategoryResource::make($this->whenLoaded('category')),
'brand' => BrandResource::make($this->whenLoaded('brand')),
'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()
$this->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values()
),
'variants' => $this->when(
$request->route()?->getName() !== 'productos.index',
fn () => ProductVariantResource::collection($this->whenLoaded('variants'))
),
'variants' => ProductVariantResource::collection($this->whenLoaded('variants')),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];