


This is commonly known as N+1 query problem. So if there are N number of posts, it will make N+1 queries( 1 query to retrieve posts and N queries to retrive author for each post). $posts = Post::chunk(100, function($posts)Īs you can see, we have one query to retrieve posts, and 5 queries to retrieve authors of the posts(Since we assumed we have 5 posts.) So for every post it retrieved, it is making one separate query to retrieve its author. option 1: Using chunk // when using eloquent To avoid issues when dealing with large datasets, we can retrieve a subset of results and process them as below. What if this table has 1 million rows? We will easily run out of memory. The above examples will retrieve all the records from the posts table and process them. $posts = DB::table('posts')->get() // when using query builder $posts = Post::all() // when using eloquent To retrieve a large set of results from a table called posts, we would usually do like below. If your application needs to process large set of records, instead of retrieving all at once, you can retrieve a subset of results and process them in groups. This tip mainly focuses on improving the memory usage of your application when dealing with large datasets. I shared tips for optimizing your mysql, eloquent and raw database queries. If your application is running slow or making a lot of database queries, follow the below performance optimization tips to improve your application loading time.
