Reader Stacks

Laravel Eloquent Quick Wins: Today's Records, Single Columns, and Group-Wise Latest Rows

Three small, specific Eloquent patterns that come up often enough to be worth knowing directly rather than re-deriving each time.

Laravel Eloquent Quick Wins: Today's Records, Single Columns, and Group-Wise Latest Rows

These three small, specific Eloquent query patterns come up often enough in real reporting and dashboard code to be worth knowing directly.

Getting today's records

$todaysOrders = Order::whereDate('created_at', today())->get();

whereDate() compares only the date portion of the column, and Laravel's today() helper returns a Carbon instance representing midnight of the current day — combined, this correctly captures every record from today regardless of the exact time each was created.

Getting a single column's value without loading the whole model

$email = User::where('id', $id)->value('email');

value() runs a query limited to just the one column requested and returns that scalar value directly — more efficient than User::find($id)->email, which fetches every column on the model just to read one of them.

Getting a single column's values across many rows

$emails = User::where('active', true)->pluck('email');
// a flat Collection of email strings, not full User models
$emailsById = User::pluck('email', 'id');
// a Collection keyed by id: [1 => 'alex@example.com', 2 => 'sam@example.com', ...]

pluck() with a second argument uses that column as the resulting collection's keys — genuinely useful for building a quick lookup map without a separate loop to re-key the results.

Getting the latest record within each group (group-wise maximum)

// the single latest order per customer
$latestPerCustomer = Order::select('orders.*')
    ->join(DB::raw('(SELECT customer_id, MAX(created_at) as max_created_at FROM orders GROUP BY customer_id) as latest'), function ($join) {
        $join->on('orders.customer_id', '=', 'latest.customer_id')
            ->on('orders.created_at', '=', 'latest.max_created_at');
    })
    ->get();

This "group-wise maximum" pattern — finding the single latest (or highest, or lowest) row per group — genuinely doesn't have a simple one-line Eloquent method, since a plain groupBy() with MAX() only returns the maximum value itself, not the full row it came from. The subquery-join approach above is the standard SQL solution to this specific, common problem.

A simpler alternative for a smaller dataset: fetch and group in PHP

$latestPerCustomer = Order::orderByDesc('created_at')
    ->get()
    ->groupBy('customer_id')
    ->map(fn ($orders) => $orders->first());

This is simpler to read and avoids the raw SQL subquery, but it fetches every order into memory before grouping — a reasonable trade-off for a smaller table, but the database-side subquery join above scales considerably better for a table with many rows per group.