Support the ongoing development of Laravel.io →
Database Eloquent

I have two models: Order and Item. There is a many-to-many relationship with a pivot table linking an Order with multiple Items. (so multiple orders can have the same card, and a card can be on multiple orders.)

I also have an additional attribute quantity in the pivot table, which has order_id and item_id.

How can I, when creating the order and saving it, add multiple items with the quantity attribute added?

The code that I currently am using (which does not work with attach()):

    $order = new Order;
    $item_quantities = [];
    foreach ($request->input('items') as $item) {
        $item_quantities[] = [Item::find($item['itemID']), ['quantity' => $item['quantity']]];
    }
    $order->items()->attach($item_quantities);
    $order->save();
Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mseymour mseymour Joined 25 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.