Optimizing Eloquent Relationship Loading in Laravel Controllers
The logic currently residing in your controller exhibits a classic performance bottleneck known as the N+1 query problem. By iterating through a collection of Product models and calling $product->products_id followed by a fresh database lookup (Product::find($products_id)->skus) for every single item, you are effectively telling Laravel to execute one initial query to fetch all products, plus one additional query for each product's relationship. If you have 100 products, that is 101 queries executed in rapid succession. While this might seem negligible for a small dataset, it scales linearly and will eventually degrade API response times significantly as your inventory grows.
The solution lies in leveraging Eloquent's eager loading capabilities. You should access the relationship data directly on the model instance using the load() method or define a scope that includes the relation, rather than fetching the parent record again inside the loop. Since your relationship is defined as Product hasMany Sku, the syntax to load these associated records is straightforward:
$products = Product::with('skus')->get();
This single query retrieves all products and their corresponding SKUs in one go (or a minimal number of queries depending on the specific optimization strategy), drastically reducing database round-trips. In your controller's index method, you can then iterate through $products, where each object already contains its loaded skus relation accessible via $product->skus.
However, there is a subtle architectural consideration regarding your model definition. You mentioned that Product hasMany Sku using products_id. In standard Laravel conventions, the foreign key usually resides on the "child" table (the Skus table), pointing back to the parent (Products). If your foreign key products_id is indeed on the Skus table, your relationship definition in the Sku model should likely look like this:
public function product()
{
return $this->belongsTo(Product::class);
}
Conversely, if you intend to retrieve SKUs for a product, the relationship in the Product model acts as an inverse. If the foreign key is on the Sku table, Eloquent can automatically detect this if the product_id column exists on the skus table and matches the primary key of the products table. You do not need to manually specify the foreign key in the Product model unless you are using a custom inverse relationship name or a specific constraint that differs from the default naming convention.
Regarding your question about where this logic fits within a repository pattern: The repository should encapsulate data retrieval strategies, including eager loading configurations. Instead of pushing database queries directly into the controller, the ProductRepository would return a collection of models with relationships loaded. This keeps the controller thin and focused on HTTP response formatting rather than data fetching.
// In ProductRepository.php
public function getAllWithSkus()
{
return Product::with('skus')->get();
}
In your ProductController, you would then simply call $this->productRepository->getAllWithSkus() and pass the result directly to your view or JSON response builder. This separation of concerns ensures that complex querying logic remains hidden from the HTTP layer.
A critical pitfall to avoid when working with relationships is assuming that eager loading will always return data for every parent record. If a product has no associated SKUs, the skus property on the model will be an empty collection ([]), not null. This distinction is important if you are iterating over results and expecting specific data structures, as checking for existence requires verifying the collection count rather than treating it as a boolean true/false value.
