php - Laravel Eloquent create related item doesnt save
I encounterd a strange issue / bug today.
I have an orders table and a table for the assigned products (order_items) Everything works fine when creating a new order, the items are saved as they should be.
$order = Orders::create($request->all());
if (!empty($order)) {
foreach ($request->get('items') as $item) {
$item['order_id'] = $order->id;
OrderItems::create($item);
}
}
The issue is that I can't add items later on, for whatever reason. I'm not getting any errors or wrong responses, even the auto-increment of the order_items table increases.
Orders::findOrFail($id)->update($request->all());
if(isset($data['items']) && is_array($data['items'])) {
foreach ($data['items'] as $item) {
if (!empty($item['id'])) {
OrderItems::findOrFail($item['id'])->update($item);
continue;
}
$item['order_id'] = $id;
OrderItems::create($item);
}
}
Answer
Solution:
If your item is not found, this will throw an exception and exuction of your script will halt.
OrderItems::findOrFail($item['id'])->update($item);
You need to catch the exception like this:
try {
OrderItems::findOrFail($item['id'])->update($item);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
$item['order_id'] = $id;
OrderItems::create($item);
}
Source