'show relation table based on the parent table column in laravel
I want to show the ProductAttributes relation based on the product's attribute_status column.
Here is my code:
Product::with('productImages', 'productReviews', 'user.vendors', 'subchildcategories', 'ProductAttributes')
->where('category_id', $request->category_id)
->where('products.status', 1)
->get();
Solution 1:[1]
Try this:
Product::where('category_id',$request->category_id)
->where('products.status',1)
->with('productImages', 'productReviews', 'user.vendors', 'subchildcategories', 'ProductAttributes')
->get();
Solution 2:[2]
$products = Product::with(['productImages', 'productReviews', 'user.vendors', 'subchildcategories', 'ProductAttributes'])
->where('category_id',$request->category_id)
->where('products.status',1)
->get()
->map(function ($product) {
$product->productAttributes = $product->attribute_status == 1 ? $product->productAttributes : null;
return $product;
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | matiaslauriti |
| Solution 2 | matiaslauriti |
