Skip to content

Don't Filter in PHP What the Database Can Filter

Quick Tips•
November 16, 2026

Subscription::all() loads every row into a collection of hydrated models, then ->filter() throws most of them away. With a million subscriptions and a few thousand active ones, the request builds a million model objects in PHP memory to keep a few thousand, and can hit memory_limit before the filter runs.

Don't do this:

PHP
<?php declare(strict_types=1); namespace App\Reporting; use App\Models\Subscription; use Illuminate\Support\Collection; final readonly class ActiveSubscriptions { public function get(): Collection { return Subscription::all() ->filter(fn (Subscription $subscription): bool => $subscription->status === 'active'); } }

Do this instead:

PHP
<?php declare(strict_types=1); namespace App\Reporting; use App\Models\Subscription; use Illuminate\Support\Collection; final readonly class ActiveSubscriptions { public function get(): Collection { return Subscription::query() ->where('status', 'active') ->get(); } }

The where clause runs in SQL, so the database returns only the active rows and PHP hydrates only those. Memory use follows the number of active subscriptions, not the size of the table.