filtering the model based on a relationship laravel

So my code is

$categories=Category::where('user_id', $store->id)->whereHas('childrenCategories', function($q) use ($id){
            $q->where('user_id', $id);
        })->orwhereHas('products', function($q) use ($id) {
            $q->where('auth_id', $id);
        })->with('products', 'childrenCategories')->latest()->get();

I want to get all children categories with and products with given id but this code doesn’t seem to work. As children categories with user_id other than id are also being returned. Sorry, I am relatively new to Laravel. And I thought this would be a good platform to ask. Also, I can share the relationships if you want me to.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I solved this with the following. Thanks, @lagbox for your time.

$categories = Category::with(['childrenCategories' => 
$childrenClosure = function ($query) use ($id) {$query->where('user_id', $id);}, 'products' 
=> $productsClosure = function ($query) use ($id) {$query->where('auth_id', $id);}])
->where('user_id', $store->id)
->where(function ($query) use ($childrenClosure, $productsClosure) {$query->whereHas('childrenCategories', $childrenClosure)
->orWhereHas('products', $productsClosure);})

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x