Usually you add a new column called order or sort with default 0, and if you want o sort/order some records then you increase the number of a specific record
Post order
What's your strategy for positioning the record? Do you rely on the id field or add custom fields where you manually set the position/order?
It depends on what I'm working with. If I work with something that is created ahead of time and them later on published, then I sort by the published at date. If I want them in the order they were created, and I use an incrementing id then I sort by that. If I need to use uuid or some other horrible id, then I'd sort by created at.
If there are things I can't sort with existing columns, and it is some kind of user defined sorting, then I would join in the custom sorting order and then order by that.
@developer654079525 If you mean sorting records, if records are to be arbitrarily sorted by users then yes, I’ll add an indexed sort_order column to the table, as well as adding a Sortable trait that applies a global scope to automatically sort records when retrieving them:
trait Sortable
{
public static function bootSortable(): void
{
static::addGlobalScope('sorted', function (Builder $builder): void {
$builder->orderBy('sort_order');
});
}
}
My strategy is, I look at the context of the query and then decide. Most often, latest() or oldest() is all that is required.
@developer654079525 It depends on the use case. If the position/order matters (e.g., for sorting items in a custom way on the frontend), I add a dedicated position or sort_order field and manage it manually. This gives full control over the order regardless of the record IDs, which may not reflect the actual intended sequence due to deletions or reordering.
If order doesn’t matter or simple chronological order is fine, I rely on the id or created_at fields.
For example, in a drag-and-drop UI where users can reorder items, a position column is essential. You update it on reorder and use it for sorting when fetching the records.
Please or to participate in this conversation.