Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahidnawaz's avatar

Need some guidance to optimize Laravel Eloquent performance

I am facing slow performance, with eloquent, I have Seller model and that connected with many other models, so it has about 8 relationships which also have relationships with their own children. I need data from all of them for generating reports, there are millions of records. It takes 10 - 12 seconds to get data, is there any way to improve performance. My database is MySQL

0 likes
6 replies
shahidnawaz's avatar

@s4muel I have implemented Attribute Casting for multiple fields in models, as I need certain values in certain format, and I am using paginate() as I only need 50 records per page.

s4muel's avatar

@shahidnawaz you might get 50 records in the end, but due to loaded related models, you might get to pretty big number of instantiated models that bloats and slows you down. try to narrow it down and load as little as possible

edit: and if you have a debugbar or clockwork, try to explore the queries and find the slowest/most run query

1 like
tykus's avatar

Generally but not always, I prefer to avoid Eloquent whenever generating reports; the amount of data tends to be too great. What aspects of Eloquent do you use / need in the reports that cannot be replicated in a raw query?

1 like
shahidnawaz's avatar

@tykus I can get data with raw queries, But I want to know how to make it better with Eloquent, there are a lot of nested relationships, and also I am using Attribute Casting in Models.

tykus's avatar

@shahidnawaz if you must use Eloquent, then the suggestions by @s4muel above are a good beginning. Not withstanding, there will be some overhead in PHP to hydrate the Models and make the associations which is unavoidable. Can you see where the 10-12 seconds are being spent?

1 like

Please or to participate in this conversation.