netdjw
netdjw

Reputation: 6007

How to show Laravel model with belongsToMany connection if has specified connection?

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

Answers (2)

Kapitan Teemo
Kapitan Teemo

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

Kamal Paliwal
Kamal Paliwal

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

Related Questions