9 months ago

A Nested query

Posted 9 months ago by ehabafia

I have a Category / Products / Users I need to get all Categories of All Products for a specific user. I was able to make selecting a product for a specific User but I couldn't tell how to get all the categories of these products.

Products and Users relationship is ManyToMany. The relationship between product belongsTo Category and Category hasMany Products

Here is what I made:

$products = Product::byUser(auth()->id())->get();
public function scopeByUser(Builder $query)
    return $query->whereHas('users', function ($q) {
        $q->where('id', auth()->id());

But I couldn't make it in a way to have:

$products = Category::productsByUser(auth()->id());

So that I can get all the categories and all the products of the loggedIn user.

Please sign in or create an account to participate in this conversation.