Loctarogar
Loctarogar

Reputation: 620

Laravel filtering one to many relations

I have Product and Category models tied one to many.How to filter Products by category? In template i have

 <a href="{{ route('product.productsByCategory', $category->id) }}" class="list-group-item">{{ $category->name }}</a>

How to write function to filter Products with Category?

 public function productsByCategory($category_id){
   $products = Product:: ????
   return view("layouts._productsByCategory", compact("products"));

Answer is

$products = Product::where('category_id', $category_id)->get();

Upvotes: 0

Views: 70

Answers (2)

apokryfos
apokryfos

Reputation: 40663

You might find it easier to go via the category:

public function productsByCategory($category_id){
    return view("layouts._productsByCategory", [
       'products' => Category::with('products')->find($category_id)->products
    ]);
}

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You can use:

$products = Product::where('category_id', $category_id)->get();

or

$products = Product::whereHas('category', function($q) use ($category_id) {
               $q->where('id', $category_id);
           });

assuming you set category relationship in Product model.

Upvotes: 2

Related Questions