I have two models: Order
and Item
. There is a many-to-many relationship with a pivot table linking an Order
with multiple Item
s. (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();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community