Laravel Code Review | Tests, Readability and Eloquent
I received a code snippet for review on what can be improved. First, let's write automated tests to ensure the code works, and then make some changes for readability and performance.
2022-06-08 11:00:00 - Laravel Daily
When you do User::has('overdueInvoices')->get() , the 'overdueInvoices' relationship is not being eager loaded.
Same thing with the invoice.items relationship. Also, checking if an item is a product could be done in the query itself.
It's ugly, but I think there would be a performance gain from querying the users in the following way:
$users = User::query()
->has('overdueInvoices')
->with([
'overdueInvoices.items' => function ($query) {
$query->where('is_product', true);
}
])
->get();
Regards,
Inti Pontt
Thanks, valuable improvement!
I'm glad when the visitors more valuable content to my own tips.
I will put this comment as a pinned one.