php - Laravel working with nested collection delete nested branch
Get the solution ↓↓↓unable to delete all nested branches where"product" => null
Have a query
$cartWhere['user_id'] = $user_id;
$cartWhere['site_id'] =$currentSite->id;
$item = Cart::select('product_id','quantity')->with(['product' => function($product) use ($search){
$product->join('product_translations', 'products.id', '=', 'product_translations.product_id');
$product->where( 'product_translations.name', 'LIKE','%'.$search.'%');
},'product.manufacturer:id,name'])
->where($cartWhere)->get();
then I receive collection that has all filtered carts but some of these carts have a relation with product => null
1 => App\Models\Cart {#736 в–ј
...
#original: array:2 [в–ј
"product_id" => 1
"quantity" => 2
]
...
#relations: array:1 [в–ј
"product" => App\Models\Product {#785 в–¶}
]
}
2 => App\Models\Cart {#736 в–ј
...
#original: array:2 [в–ј
"product_id" => 2
"quantity" => 2
]
...
#relations: array:1 [в–ј
"product" => null
]
}
sorry for my English
Answer
Solution:
You can filter them from the results using the collections filter() method
$item = Cart::select('product_id','quantity')
->with(['product' => function($product) use ($search) {
$product->join('product_translations', 'products.id', '=', 'product_translations.product_id');
$product->where( 'product_translations.name', 'LIKE','%'.$search.'%');
}, 'product.manufacturer:id,name'])
->where($cartWhere)
->get()
->filter(function ($cart) {
return $cart->product !== null;
});
Answer
Solution:
Along withwith
you should usewhereHas
. So the result will not include any relation withnull
value. So this way you can also avoid the extrafilter
method used.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.