Photo by Colin Maynard on Unsplash
Vous parlez français ? Lisez ce billet sur mon blog :)
When I started using Laravel, I really enjoyed the fact that I could simply grab all my data with a simple line of code:
$products = Product::get();
All my products, in a beautiful little collection, waiting to be deliciously presented in an appealing view or handled with care in an data processing algorithm.
The problem is that sometimes / often (pick the right one) I only need a few informations from my products, like the name and price and no more. I don't need the extra informations my database could hold. And the code above is loading everything: name, price, description, maybe a picture and so on.
Get into the habit of specifying the desired columns when executing queries to the database, even if they are simple or not very demanding. This is a reflex that can offer us precious seconds of optimization during more complex operations.
For instance, if my view only needs name and price :
// 👎 I am loading every columns
$products = Product::get();
// 👍 I only load the specific columns I need
$products = Product::select(‘name’, ‘price’)->get();
The benefit is imperceptible on such simple queries and a small dataset, but it becomes essential at a certain level and helps to make the difference between a slow and fast query.
See you soon for another trap I fell for.
Top comments (0)