CodexBloom - Programming Q&A Platform

Laravel 10: How to optimize database queries when using complex joins in Eloquent?

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
laravel eloquent performance PHP

I'm sure I'm missing something obvious here, but I'm working on a personal project and I tried several approaches but none seem to work... I'm currently working on a Laravel 10 application that requires fetching data from multiple related tables using Eloquent. The query involves several complex joins, and while it works, the performance is noticeably slow, especially when the database grows in size. Here’s the query I’m using: ```php $results = DB::table('orders') ->join('users', 'orders.user_id', '=', 'users.id') ->join('products', 'orders.product_id', '=', 'products.id') ->select('orders.*', 'users.name as user_name', 'products.name as product_name') ->where('orders.status', '=', 'completed') ->get(); ``` The total number of records in the `orders` table has surpassed 100,000 and I’m starting to see important latency when executing this query. I've already tried adding indexes on the `user_id` and `product_id` fields, but the scenario continues. Additionally, I considered using Eloquent relationships instead of raw joins, but I’m unsure if that would enhance performance or complicate things further. I’m also seeing some unexpected behaviors, like occasionally receiving duplicate entries in the results. After reading some documentation, I learned about query caching and eager loading, but I'm not sure how to implement these optimally in this scenario. Can anyone suggest best practices for optimizing such database queries in Laravel, or any specific changes that could help improve the performance here? For context: I'm using Php on macOS. What's the best practice here? For context: I'm using Php on macOS. I'm working in a Ubuntu 22.04 environment. Thanks for any help you can provide!