Roman Khegay
Roman Khegay

Reputation: 183

Returning Laravel many-to-many relations with clause options

There is code in Laravel:

$product = Product::where('slug', $slug)->with('types')->with('brand')->firstOrFail();

return $product;

I'm retrieving array with types array and brand array.

Types has boolean options "is_active"

How I can return $product with types that is_active

ex.

$product = Product::where('slug', $slug)->with('types')->with('brand')->where('types.is_active', '=', '1')->firstOrFail();

Upvotes: 0

Views: 40

Answers (2)

osukono
osukono

Reputation: 15

If you need only products which type is active, you can also filter them:

$product = Product::with([
    'types' => function($query) { $query->where('is_active',true); },
    'brand'
])
->where('slug', $slug)
->whereHas('types' => function($query) { $query->where('is_active',true); },
->firstOrFail();

Upvotes: 0

Sérgio Reis
Sérgio Reis

Reputation: 2523

Try this out,

$product = Product::where('slug', $slug)->with([
   'types' => function($query){ $query->where('is_active',true); } ,
   'brand'
])
->firstOrFail();

Source docs, https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads

Upvotes: 3

Related Questions