$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[June 07, 2024] Eloquent ORM

Eloquent Date Range Queries

Eloquent Date Range Queries

────────────────────────────────────────────────────────

Eloquent Date Range Queries

Tip: whereBetween for Dates

Post::whereBetween('created_at', ['2024-01-01', '2024-12-31'])->get();

Gotcha: whereDate vs where

Post::whereDate('created_at', '2024-01-15')->get();

whereDate compares only the date portion, ignoring time.

Tip: Carbon Comparisons

Post::where('created_at', '>=', now()->subDays(30))->get();

Gotcha: Timezone Awareness

Post::where('created_at', '>=', now()->setTimezone('UTC')->startOfDay())->get();

Tip: whereMonth and whereYear

Post::whereYear('created_at', 2024)->whereMonth('created_at', 6)->get();

Gotcha: Index on Date Columns

Date range queries benefit from indexes. Add created_at index for performance.

Tip: Use cursor() for Memory-Neutral Iteration

When exporting 100K rows, get() loads everything into memory. cursor() uses yield and keeps memory flat regardless of row count. Perfect for artisan commands.

Tip: whereHas() vs load() — Two Different Things

whereHas() filters the parent query by relationship existence. load() eager-loads relationships AFTER the query. Mixing them up is a common source of logic bugs.

Gotcha: withCount() Adds a Subquery

withCount('comments') runs a correlated subquery on every row. On large tables, this can be slower than a separate query. Profile before relying on it.

Senior Insight

Date range queries in Laravel are straightforward with whereBetween('created_at', [$start, $end]), but there's a subtlety: the time component. whereBetween uses the time as well as the date, so a query for 'today' only includes records up to the current time. I always use whereDate('created_at', $date) for full-day comparisons and whereBetween with explicit start/end-of-day boundaries. Also, store dates in UTC and query in UTC.

Source: Laravel Docs (https://laravel.com/docs/eloquent), Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/eloquent)

────────────────────────────────────────────────────────
<-- back to posts