TechnicalEloquent performance

Eloquent performanceLesson 20 of 28

Ordering By Custom Algorithms

Custom order? Turn it into a SQL expression, then index it if needed.

1 min readIntermediateLesson

Eloquent performance20

The problem

Statuses sort alphabetically (approved, completed, requested), not in workflow order. And "activity" should weigh comments as two votes each.

The fix

Describe your custom order in SQL so the database can sort by it.

✕ Instead of this

$query->orderBy('status', $direction);
// approved, completed, requested (alphabetical)

✓ Do this

$query->orderBy(DB::raw("case
    when status = 'requested' then 1
    when status = 'approved'  then 2
    when status = 'completed' then 3
end"), $direction);

The benefit

Statuses sort in workflow order: requested, approved, completed.

More detail

The sort is chosen from ?sort=...&direction=...:

->when(request('sort'), function ($query, $sort) {
    switch ($sort) {
        case 'title':    return $query->orderBy('title', request('direction'));
        case 'status':   return $query->orderByStatus(request('direction'));
        case 'activity': return $query->orderByActivity(request('direction'));
    }
})

Activity reuses the counts from withCount(['votes', 'comments']):

$query->orderBy(DB::raw('votes_count + (comments_count * 2)'), $direction);

Watch out

  • On big tables, index the CASE expression with $table->rawIndex("(case ... end)", 'features_status_ranking_index').
  • If activity sorting gets slow, store an indexed activity_rank column and update it on each vote or comment.

Frame from lesson 20

Sorting by activity: each row shows votes, comments and the computed rank in brackets. For example, 29 votes + 2 comments × 2 = 33.

Key takeaway

Custom order? Turn it into a SQL expression, then index it if needed.

Check yourself

A feature has 29 votes and 2 comments. What's its activity rank?

Reveal answer

✓ Answer

29 + (2 × 2) = 33.