I have two Model named Product
and Category
. Admin can change the status of Product
and Category
.
Here Product
and Category
has many to many relations. So that, all Product
can belongs to multiple Category
Now at my user panel,
I want to show that all Product
whose all Category
's status is active.
CodePudding user response:
**Solution is**
$products = Product::with('category')
->whereHas('category', function ($query) {
$query->where('status', 'active'); // use your column & condition
})
->get();
CodePudding user response:
you can do this in your product model
public function categories(){
return $this->belongsToMany(Category::class, CategoryProduct::class, 'product_id', 'category_id');
//->withPivot([]); if you need anything from the pivot table for any reason you can add the column names in the array
}
this is assuming that the pivot table have the columns product_id and category_id
$products = Product::with('categories')
->whereHas('categories', function ($query) {
$query->where('categories.status', 'active');
})
->get();
inside the where the word categories is the table name