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

cecily's avatar

Laravel - how to use model's ID inside belongs to many relationship query?

Models:

Products
Variants
VariantValue

// Product.php
public function variants()
{
    return $this->belongsToMany(Variant::class, 'product_variant', 'product_id', 'variant_id')
        ->with([
            'values' => function ($builder) {
                return $builder->whereHas('products', function ($q) {
                    return $q->where('products.id', $this->id);
                });
            },
        ]);
}


// Variant.php
public function values()
{
    return $this->hasMany(VariantValue::class);
}


// VariantValue.php
public function products()
{
    return $this->belongsToMany(Product::class, 'product_variant_value', 'variant_value_id', 'product_id');
}

The above works if we do the following:

Product::first()->variants()->get()->toArray()

But, it doe NOT work if we do the following (the values array is empty):

Product::with('variants')->get()->toArray()

Meaning the issue is that the product ID is not available inside the belongs to many query:

return $q->where('products.id', $this->id);

Any idea how I can make this work? The goal is to load relationship using:

Product::with('variants')->get()
0 likes
2 replies
cecily's avatar

So basically, this should be dynamically the product ID

return $q->where('products.id', $this->id);

So close but I just can't figure it out

Please or to participate in this conversation.