Which Laravel version are you using?
If version 8, you could try using an upsert operation:
Hi All - had a situation come up, where the user has a list present in the front end which is sortable via click and drag.
Now what the backend receives from this is something that looks like this
[
[
'order'=>1,
'value'=>'id of first item',
],
[
'order'=>2,
'value'=>'id of second item',
],
...
]
So - My question comes around the most efficient way of doing this, because these lists can actually be up to around 100 items in some cases.
The default way, which is making me uncomfortable is something like this
foreach($new_order as $li) {
\App\Models\Item::find($li['value'])
->update(['sort_order'=>$li['order']]);
}
because that seems like every time the user triggers a re-sort, then the there will be 100 database updates - which may be easy... but it feels like that's... not great.
The second way which takes more of the database work into the front-end.. which can have it's own problems is this - keep in mind I already have the items in the controller at this point through a
$items = $list->items()->get();
foreach($new_order as $li) {
if ($items->firstWhere('id', $li['value'])->sort_order !== $li['order']) {
\App\Models\Item::find($li['value'])->update(['sort_order'=>$li['order']]);
}
}
The second one requires that PHP do some comparison work - which I feel like usually isn't great, but doing 100+ db queries every second where some of the values will be updating nothing also seems like a bad call.
What do you guys think?
Which Laravel version are you using?
If version 8, you could try using an upsert operation:
Please or to participate in this conversation.