Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jarmark's avatar

How do you handle with reordering items?

In my tables I often use field order to let users to manage order of their items. We can imagine some actions like creating new item, deleting old item, moving up item or moving it down. These actions affects on items order.

What parts of Laravel do you use to handle this situations? In my opinion it is good to use model's events like or creating or deleting.

For example when we delete t-shirt in products table we get https://s23.postimg.org/lmc79i4kr/table.png

How do you handle with reordering items? Do you use special libraries?

0 likes
5 replies
jarmark's avatar

It is not so easy. For example when you one delete one model, you have to reorder rest of them. In this case you generate PATCH request for each model from front-end layer.

How do you do it? Can you give little example how you handle it?

If I understand you properly, you use REST approach to get your data. I use Resource Controllers to handle routes, but I do not use REST.

Snapey's avatar
Snapey
Best Answer
Level 122

you are possibly overthinking it.

the only time you need to reorder is when the user specifically requests it...

adding a new item - put it at the end of the list. query the database and get the last item, get the sequence number, add one and save the new item as the next sequence

removing an item - just delete it. there will be a gap in the sequence number, but so what? Sorting the items ascending or descending will still work without sequential numbering.

reordering - accept a list of model ids and iterate through them giving the first 0, the next 1, 2, 3 etc. Pay no attention to what number they had before.

4 likes
jarmark's avatar

@Snapey Great answer. What about moving model up or down? Just switch sequence number between two models?

Btw how to get previous model or next model having only current model and not having a collection :)?

Snapey's avatar

front end, i have used dragular to allow the user to reorder, then a save button that does an ajax post with the array of ids in their new order. Yes it's more sql updates than might be necessary but it means the user can just drag and drop and I don't need to try and diff the before and after lists.

your Btw. it depends what function you are trying to perform at the time. it's possible but if you forget about the option of 'swapping' two items then you never need to work out the adjacent models.

1 like

Please or to participate in this conversation.