Create or update rows Laravel

Viewed 48

I try to update or create a table with data from request, on update it works, but on create I can do just for 1. So, if I have 4 new items, just 1 is saved, not sure why, and no errors. If I dump the request I have all values.

$answers = new LkpAnswer;

    foreach ($request->items as $key => $item) {
        if (isset($item['id'])) {
            $answers->where('id', $item['id'])->update($item);
        } else {
            $answers->fill($item)->save();
        }
    }
2 Answers

Please Try the following code:

foreach ($request->items as $key => $item) {
    if (isset($item['id'])) {
        LkpAnswer::where('id', $item['id'])->update($item);
    } else {
        $answers = new LkpAnswer; //new up an empty model(object) then fill it with your array of data, and finally save it.
        $answers->fill($item)->save();
    }
}

This should be achievable neatly with built in methods:

foreach ($request->items as $item) {
    LkpAnswer::updateOrCreate($item['id'],$item);
}

Make sure that the relevant fields are fillable - see mass assignment protection.

Related