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

chahal's avatar

Handle Many to Many with a field

I am having a situation where I have 2 tables users & products. I need a different price for many users.

So I am looking to make a pivot table that will handle users and products in many to many relationships. In that pivot table, I am planning to add a product_price field as well which will be further used for different prices for different users.

Just wanted to know if there is a better alternative.

0 likes
6 replies
chahal's avatar

@Sinnbeck I want to fill this price field with a default_price field of the Product model. How can we do that here?

$user = User::factory()
            ->hasAttached(
                Product::factory()->count(3),
                ['price' => ??]
            )
            ->create();

I tried

$user = User::factory()
            ->hasAttached(
                Product::factory()->count(3),
                ['price' => function(Product $product){
							return $product->default_price;
				}]
            )
            ->create();

But that didn't work. Something seems to be missing there.

chahal's avatar

Thankyou @sinnbeck for your reply, Just a question, is this the best possible way to do this or you would have done this differently?

Sinnbeck's avatar

@chahal It is how I would most likely do it (unless other details are left out)

Lumethys's avatar

db:

users[ id, .... ]
products [ id, ..... ]
user_product [id, user_id, product_id, price, ..... ]

model:

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

//product
	public function users()
	{
		return $this->belongsToMany(User::class);
	}

Controller:

// user 1 and his products' price
	$user = User::with('products')->find(1);
	$priceArray = $user->product->pivot->price 

// product id 1 and its users' price
	$product = Product::with('users')->find(1);
	$priceArray = $product->user->pivot->price;

you could modify the method name if you dont like ->pivot():

	public function users()
	{
		return $this->belongsToMany(User::class)->as('whatever');
	}

	/////
	
	$user->products->whatever->price

Please or to participate in this conversation.