Reputation: 6007
I have this product model:
public function categories() {
return $this->belongsToMany('App\Category', 'product_categories');
}
And in my controller:
public function search(Request $request) {
return Product::with([
'categories' => function($categories) use ($request) {
// ...
}
]);
}
If I try to use $request
in the categories
function it's search only in categories, but shows all products.
How do I show only that products whitch has defined categories in $request->category_id
?
Upvotes: 0
Views: 41
Reputation: 2164
you may use the whereHas
keyword in laravel:
public function search(Request $request) {
return Product::with('categories')
->whereHas('categories', function ($query) use ($request){
$query->where('category_id', $request->category_id);
})->get();
}
Here is the docs
Upvotes: 1
Reputation: 1301
You can search it in following way:
public function search(Request $request) {
return Product::with('categories')
->whereHas('categories', function ($q) use (request) {
$q->where('id', $request->category_id);
});
}
Upvotes: 0