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

vovkacrackhead's avatar

Relationship m2m, Eloquent

I have 3 tables: orders, products, order_product. There are 4 columns in order_product table: id, order_id, product_id, count. I already make a relationship between tables. How can i create new order and immediately attach him few products with count from form? I created new func in ordercontroller:

public function newOrder(){
    $order = new Order([
        /*data of order*/
    ]);

    $order->save();
}

what should i do next ?

0 likes
1 reply
kylemilloy's avatar

Documentation available here: https://laravel.com/docs/5.8/eloquent-relationships

You'd do something like:

// in App\Order.php

public function products() {
  return $this->belongsToMany(Product::class)
    ->withPivot([
        'count',
    ]);
}

// in your function

public function newOrder() {
    $order = Order::create($attrs)
        ->products()
        ->attach($product_id, [
            'count' => 1 // or whatever value this needs to be.
        ]);
}

The attach function also takes an array so you can send it multiple IDs.

Please or to participate in this conversation.