Stop repeating your where() clauses in Laravel 🔁

php dev.to

If you've ever needed multiple aggregate queries (count, sum, avg) on the same filtered data, you've probably copy-pasted the same where() chain over and over.

The problem? Laravel's query builder is mutable. Once you run one query, chaining more methods onto it doesn't give you a "fresh" copy of your filters.

The fix: PHP's clone keyword.

$query = Event::where('status', 'active')
    ->where('created_at', '>=', now()->subDays(30));

$totalCount = (clone $query)->count();

$groupedCount = (clone $query)
    ->selectRaw('count(*) as count')
    ->groupBy('event')
    ->get();
Enter fullscreen mode Exit fullscreen mode

Same filters, zero repetition, no leftover state messing up your results.

Small trick, but it keeps analytics/reporting code a lot cleaner.

Full write-up with more examples 👇
Read Article

Source: dev.to

arrow_back Back to Tutorials