API resource collection N+1 performance

Posted 3 months ago by paul-a-byford

hey everyone, please can you offer your thoughts on how best to solve a performance problem when I use API resource collections.

i'm finding from laravel telescope that the resource collection I've created executes 200 database queries to generate the response!

i've created an api resource class using artisan and updated the generated toArray method to return the various attributes I require on the resource. this includes items I fetch via relationships - which seems to be the cause of the multiple database queries.

from my controller I fetch the raw data as an eloquent collection and pass that to the static collection method on the api resource - similar to as described in the docs https://laravel.com/docs/5.8/eloquent-resources#resource-collections

i've attempted to use lazy eager loading in my controller before passing it to the api resource collection method, which reduced the query number a little. on attempted to debug it seems that the api resource collection method maps through the collection and calls toArray each time. when the toarray runs each time laravel runs individual database queries each time, rather than using the data I already eager loaded in the controller.

thanks

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.