Brotzka
Brotzka

Reputation: 2785

Laravel filter whole collection or use scopes

I am implementing some filters for a specific Eloquent-model.

Right now I fetch all available products from the database wrapping the command in laravels Cache::remember () function. Then I pass this collection through a series of Filter-Classes. In each filter-class I perform a $productCollection->filter() action which returns all fiting products. At the end, I get all products fitting the given filter parameters.

Now I wonder if this is a good practice or if it would be better to use scopes or filter direct during the database query.

Some filters filter for a direct match (e.g. brand must be id 4). Others have a set of possible fits (e.g. category must be id 3, 4 or 7).

Upvotes: 0

Views: 1064

Answers (1)

Mateus Junges
Mateus Junges

Reputation: 2602

It depends on your application scale and the size of the collections you are filtering. If you have a small collection, with about 100 models, it will make no difference. But, if you need to filter 1k+ models, it's better to use a query scope directly with you eloquent model. The query scopes will return only the registers which match with the scope condition, while the ->filter() method will iterate over all your models to, then, take only those models that matches with the rule you specify inside the filter callback function. In resume, it is always better to return only the records that you need, since it remove the need to iterate through all the records and return just a half or less of them. Besides that, the query scopes allow you to define common sets of constraints that you may re-use throughout your app, while, if using collection filter, you need to rewrite the same filter every time you want to use it.

The documentation about query scopes.

Regards, Mateus.

Upvotes: 2

Related Questions