Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Shiva's avatar
Level 5

How to get a category of a product

I'm not sure if I can explain this properly, but I have 3 tables

users products categories

and what I'm trying to do is get the category that is attached to a product that is attached to a user. So far I'm only able to get up to the product but I'm not sure how to get the category.

Here is my code

My controller

public function getProduct(User $user)
{
    $products = $user->product;

    return [
        'products' => $products
    ]
}

and here is my User.php

public function products()
{
    return $this->hasMany(Product::class);
}

My Product.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function category()
{
    return $this->belongsTo(Category::class);
}

and my Category.php

public function products()
{
    return $this->hasMany(Product::class);
}
0 likes
2 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

Like so I guess

$products = $user->product()->with('category')->get();
Shiva's avatar
Level 5

Yes that was it thank you so much

Please or to participate in this conversation.