0
  • I have multiple tables with millions of records, and I'm facing performance challenges with my current Eloquent queries.

  • I have three tables = 'sales', 'expenses', and 'profits'

  • Each table has columns such as 'amount', 'date', and 'category_id'

  • I need to generate a report that shows total sales, total expenses, and net profit for each category on a monthly basis

  • I'm currently using Eloquent to fetch data for each category and month, but the queries are becoming slow as the data get.

// Fetch total sales for a category in a specific month
$sales = Sale::where('category_id', $categoryId)
             ->whereMonth('date', $month)
             ->whereYear('date', $year)
             ->sum('amount');
  • What strategies can I employ to optimize Eloquent queries for large datasets in Laravel?
  • Are there specific indexing techniques or caching mechanisms I should consider for better performance?
  • Is there a more efficient way to structure the database or queries to handle such reporting scenarios?
1
  • Indexes and avoid ORM (Eloquent) you can run benchmark between Sale::where('category_id', $categoryId).. vs DB::table('sales')->where('category_id', $categoryId).. Commented Jan 18, 2024 at 12:23

1 Answer 1

0

Some points to consider when you are trying to optimize eloquent queries,

  1. Always use the select() method when retrieving data from the table. Only retrieve the columns that you need. For example, you have a table named sales and you only need 2 columns, categoty_id and date that will be used then your query should be,
Sale::select('id','categoty_id', 'date')->get();
  1. If your APIs that use fetch queries are called often then try to cache the query result. You can use Redis, or Memcache for caching so your database will have less load.

  2. Use eager loading instead of lazy loading to reduce the number of queries.

  3. Always use keys like foreign keys, unique keys, etc., and also do indexing wherever required. For example, if columns like category_id and date are used frequently then make them indexed.

  4. Use laravel telescope to check query performance. It's also useful to track other things like cache, logs, events, and broadcasting. But remember you should only use it in development because it can slow your database in production.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.