I have a table which is Order
and Product
In my model: Order
can have many products
. Product
belongs to order
Below is my view:
<input type="text" name="order_name">
<input type="text" name="product_name">
<input type="text" name="order_name">
<input type="text" name="product_name">
From the view above, I have two forms whereby the users can add two form with two input.
Now my problem is how do I write the logic in the controller?
I just know the way to write insert one order with multiple product. But I don't know how to insert multiple orders with its related product.
You should use a pivot table, as it's a many to many relationship between the two tables.
Since a product belongs to not just one order but many and an order can have many products, pivot table is the way to go.
See here if you don't know what a pivot table is : http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/
They explain it in an example very similar to yours.
Try this:
$order = new Order();
$order->order_name = $request->order_name;
if($order->save()) {
$product = new Product();
foreach($request->product_name as $product) {
$product->product_name = $product;
$product->order_id = $order->id;
$product->save();
}
}