{"id":8503,"date":"2023-08-14T09:28:36","date_gmt":"2023-08-14T09:28:36","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=8503"},"modified":"2023-08-14T09:30:11","modified_gmt":"2023-08-14T09:30:11","slug":"eager-loading-for-each-loop-in-laravel","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/laravel\/eager-loading-for-each-loop-in-laravel","title":{"rendered":"Load Laravel Eloquent Relationships"},"content":{"rendered":"<h3>Introduction<\/h3>\n<p>Mainly there is two way to load the Laravel eloquent relationships Eager loading and lazy loading by default in Laravel use lazy loading.<br \/>\nIn a lazy loading where you only get one item at a time and then retrieve related items only when needed. However, in this case N+1 query problem occurs. In the case of eager load relationship are loaded at the time of parent model load.<\/p>\n<h3>Description<\/h3>\n<p>Let\u2019s understand it with some example if we have a two table for store the states and there cities. Here we have a relationship in the states table of hasMany so state have a many cities.<\/p>\n<h3>Lazy Loading<\/h3>\n<p>When we run a query to get all the states and through them, and for each state, we got the database query for cities. That is lazy loading i.e we are delaying the retrieval of the cities until we needed them.<\/p>\n<h3>Eager loading<\/h3>\n<p>In the eager loading we get all the states with their cities. So that when we are getting the states, we do not make separate database query to fetch the cities, it\u2019s already loaded with states it\u2019s called eager loading.<\/p>\n<p>Eager loading helps us to solve the N+1 query problem. Let us look at a simple example of our states and cities data.<\/p>\n<p>Let\u2019s assume we have an eloquent model <strong>state<\/strong>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\nnamespace App\\Models;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nclass State extends Model{\r\n   public function cities(){\r\n      return $this-&gt;hasMany(City::class);\r\n   }\r\n}\r\n<\/pre>\n<p>And a city model<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?php\r\nnamespace App\\Models;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nclass City extends Model{\r\n   public function state(){\r\n      return $this-&gt;belongsTo(State::class);\r\n   }\r\n}\r\n<\/pre>\n<p>Let\u2019s assume that we have 10 records in our state table for getting all those records we need to do run the below query<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">$states = State::all();<\/pre>\n<p>Then we have to go to all the cities associated with each state so we do something like this<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">foreach ($states as $state){\r\n    echo $state-&gt;cities~-&gt;count();\r\n}\r\n<\/pre>\n<p>This is what will happen with this scenario:<\/p>\n<p>The query will run once for the first time to get the 10 states, then 10 more queries to get the associated cities. That makes it 11 queries in total i.e 10(N) + 1. This is called lazy loading<\/p>\n<p>But, with the help of eager loading to get 10 states and there cities, we only need two query. Let\u2019s see it on below example<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">$states = State::with('cities')-&gt;get();\r\nforeach ($states as $state){\r\n   echo $state-&gt;cities-&gt;count();\r\n}\r\n<\/pre>\n<p>After using with method we all the record and it\u2019s run only two query for getting same amount of data and it\u2019s help to reduce the query cost.<\/p>\n<h3>Conclusion<\/h3>\n<p>All things come with some advantage and disadvantage it\u2019s up to us to use the right things at the right time . Both Eager loading and lazy loading have their own advantages and disadvantages. You can see some of them below :<\/p>\n<h3>Pros of Eager Loading<\/h3>\n<p>You got all the data in a single query.<br \/>\nThere is no wait for accessing related data because it\u2019s already loaded with there parent one.<br \/>\nLess number of query executed with db.<\/p>\n<h3>Cons of Eager Loading<\/h3>\n<p>You might get a data that you don\u2019t actually need.<br \/>\nInitially query become slow, and might bad for a lots of records.<br \/>\nOf course, it\u2019s need more memory.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Mainly there is two way to load the Laravel eloquent relationships Eager loading and lazy loading by default in Laravel use lazy loading. In a lazy loading where you only get one item at a time and then retrieve related items only when needed. However, in this case N+1 query problem occurs. In the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":8506,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[10],"tags":[],"class_list":["post-8503","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/8503"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=8503"}],"version-history":[{"count":5,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/8503\/revisions"}],"predecessor-version":[{"id":8508,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/8503\/revisions\/8508"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/8506"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=8503"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=8503"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=8503"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}