TechnicalEloquent performance

Eloquent performanceLesson 21 of 28

Filtering and Sorting Anniversary Dates

Year-agnostic dates: compare month-day and index the expression.

1 min readIntermediateLesson

Eloquent performance21

The problem

Sort users by birthday (ignoring the year), and show birthdays this week.

The fix

Compare the month and day only, add an index on that expression, and filter with the week's actual dates.

✕ Instead of this

$query->whereBetween(DB::raw("date_format(birth_date, '%m-%d')"), [
    now()->startOfWeek()->format('m-d'),   // '12-30'
    now()->endOfWeek()->format('m-d'),     // '01-05'
]);
// matches nothing in New Year week

✓ Do this

$dates = Carbon::now()->startOfWeek()
    ->daysUntil(Carbon::now()->endOfWeek())
    ->map(fn ($date) => $date->format('m-d'));

$query->whereRaw(
    "date_format(birth_date, '%m-%d') in (?,?,?,?,?,?,?)",
    iterator_to_array($dates)
);

The benefit

Works every week of the year, including the one that crosses New Year.

Results

Sort by birthday

~27 ms~5 ms

81% lower

with the expression index

More detail

Order by month-day, with a compound expression index to make it fast:

User::orderByRaw("date_format(birth_date, '%m-%d')");

// migration
$table->rawIndex("(date_format(birth_date, '%m-%d')), name", 'users_birthday_name_index');

Watch out

  • A whereBetween('12-30', '01-05') matches nothing when the week crosses New Year. Test with Carbon::setTestNow('January 1').
  • Run EXPLAIN to confirm the expression index is used.

Frame from lesson 21

The birthday scopes. orderByRaw('date_format(birth_date, "%m-%d")') orders by month and day, and scopeWhereBirthdayThisWeek() builds the week's 7 dates with daysUntil() for a whereRaw(... in (?,?,?,?,?,?,?)).

Key takeaway

Year-agnostic dates: compare month-day and index the expression.

Check yourself

Why does whereBetween fail for the week of 30 Dec to 5 Jan?

Reveal answer

✓ Answer

As text, '12-30' is greater than '01-05', so no value falls between them.