Sort users by birthday (ignoring the year), and show birthdays this week.
Sort by birthday
~27 ms~5 ms
81% lower
with the expression index
Eloquent performanceLesson 21 of 28
Year-agnostic dates: compare month-day and index the expression.
1 min readIntermediateLesson
Sort users by birthday (ignoring the year), and show birthdays this week.
Compare the month and day only, add an index on that expression, and filter with the week's actual dates.
$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
$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)
);
Works every week of the year, including the one that crosses New Year.
Sort by birthday
~27 ms~5 ms
81% lower
with the expression index
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');
whereBetween('12-30', '01-05') matches nothing when the week crosses New Year. Test with Carbon::setTestNow('January 1').
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 (?,?,?,?,?,?,?)).
Year-agnostic dates: compare month-day and index the expression.
Why does whereBetween fail for the week of 30 Dec to 5 Jan?
✓ Answer
As text, '12-30' is greater than '01-05', so no value falls between them.