Logic
- Category has Products
- Products has
brand(1),options(0 or many),tags(0 or many),rating(0 or many) - I want get every
brand,options,tags,ratingsunder current category in arrays
Note: returned data are category based not database based, so each category return different set of data based on what has been provided to that category products.
Code
Controller
public function show($slug)
{
$category = Category::where('active', 'yes')->where('slug', $slug)->with('products')->first();
return response()->json([
'data' => new CategoriesFrontResource($category),
'success'=>'Category retrieved successfully'
], 200);
}
Category model
public function products(){
return $this->belongsToMany(Product::class, 'category_products', 'category_id', 'product_id');
}
Product model
public function categories(){
return $this->belongsToMany(Category::class, 'category_products', 'product_id', 'category_id');
}
public function options(){
return $this->belongsToMany(Option::class, 'option_products', 'product_id', 'option_id');
}
public function tags(){
return $this->belongsToMany(Tag::class, 'product_tags', 'product_id', 'tag_id');
}
public function brand(){
return $this->belongsTo(Brand::class);
}
public function rating(){
return $this->morphMany(Rating::class, 'rateable');
}
Any idea how to achieve that goal?
Update
Based on Jeemusu answer here is what I have currently
$category = Category::where('active', 'yes')->where('slug', $slug)->with(['products', 'products.options', 'products.variations', 'products.brand', 'products.tags', 'products.rating'])->first();
$products = $category->products;
$tags = $products->tags->toArray();
And this is the results
Property [tags] does not exist on this collection instance.