Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e42 – Lazy Loading vs. Eager Loading (Fixing N + 1 Problem)

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e42 – Lazy Loading vs. Eager Loading (Fixing N + 1 Problem)

welcome back so in the previous episode we added 50 new customers and then when we looked at telescope at how many queries we were actually running we

realized that we have an N plus 1 problem now the n plus 1 problem simply means that level is not efficiently bringing in all of the data that it needs and the reason for this is that if

we go back to our customers index method we have our customers right so our controller is fetching the customers let's check that out customer controller so let's go to our index and we see that

we are fetching all of our customers now all of our customers let's die and dump all of our customers right now and I will set this to an array so it's easier to see and let's check out what happens

when i refresh the browser so there we are so all of our customers right now have this data but notice here that none of them have a key for their company and

that's because the company remember lives in a totally separate table so what is currently happening is that every single one of those fetches a brand new query just to fetch one single

company right so it's matching the company for that particular customer and fetching them one at a time so if you can imagine if you had thousands of records you would literally have 1,000

extra queries that you don't even need and the reason for that is that MySQL and any relational database is able to fetch all of these records in a single query so how do we fix this well the

answer is actually fairly simple so what we need to tell laravel is hey I want to bring in all of my customers however I also want to load all of their specific companies so how do we actually do that

so to do that let's modify this line right here and what we're gonna say is give me all of my customers with their company and then go ahead and fetch me all of the records now let's check out

what happens if I hit refresh when I open this up now we have this whole new key here for company and when we open that up that has the company already attached so

essentially we've already loaded that relationship so now when we use the relationship level no longer has to call all of those extra queries but instead it already has the information available

this is what we have right now let me go ahead and delete this line and I will hit refresh in our customers again and let's check out telescope notice that this one right here is the

last one it took point 16 milliseconds and there it is so now check it out we only have three queries so we are selecting our user ignore this for now that one is simply

just fetching our user that we are logged into for this section up here so ignore that query but now we only have one query for selecting all of our customers and then we are grabbing all

of our companies but this time we are grouping them all together into one big array and grabbing them all in a single query so we went from 51 queries to two queries so that is a huge improvement

especially if you have a big database with a lot of Records that you're trying to fetch and they all have relationships now imagine that we were also fetching a second or third relationship everything

gets multiplied over and over imagine you fetched four relationships on a thousand records you would literally have four thousand and one queries that you could do in three queries so that's

a huge difference between 4,000 queries to four queries so keep that in mind so once you have telescope installed it's really easy to grab them because you'll see something like this all of a sudden

you'll have a lot of queries that end in limit one if you see this pattern in your application that is a great opportunity for you to go ahead and eager load these relationships so go

ahead and find them and do the same modification that we did here you are eager loading your company instead of just letting laravel do it on the fly now this company belongs to the

relationship if you to a customer you see here that the relationship is called company and that is what's being matched to that so that is a very important lesson in laravel

remember always try to load anything that you need up ahead so that level doesn't have to take care of that for you if you have telescope installed then it's really easy to notice if you see

here a bunch of queries with a limit of 1 that is the telltale sign there you should be eager loading some sort of relationship so with that we'll wrap it up for this lesson and the next lesson

let's move on to something else

You may have heard these fancy terms or read them in a blog post but what do they mean? In this lesson, we are diving deep to find out what it means, how to detect it and ultimately how to fix and avoid it.

For the best experience, follow along in our interactive school at https://www.coderstape.com

Laravel Telescope
https://laravel.com/docs/5.8/telescope

DigitalOcean Referral
https://m.do.co/c/7dce5364ef4d

Resources
Course Source Code
https://github.com/coderstape/laravel-58-from-scratch

Hit us up on Twitter with any questions or comments @codertape (https://twitter.com/CodersTape)

About This Course

Ready to get started on your path to Laravel Artisan? In this series, we are breaking down all of the basics of Laravel to get you comfortable using the world’s most popular PHP framework. Let’s get started!

    add to database laravel admin laravel artisan Artisan Command artisan commend create artisan console artisan laravel command authentication in laravel belongsto belongsto laravel example coding tutorials create artisan command create command artisan create new command artisan Create your own crud laravel crud laravel tutorial crud resource laravel crud with file upload custom artisan commands custom artisan commands laravel custom laravel database configuration laravel database relationship digital ocean dotenv eager loading eager loading in laravel eager loading vs lazy loading laravel eloquent eloquent accessors eloquent mutators eloquent orm feature testing laravel fetching data in laravel filesystem laravel form requests full stack vue gate and policy laravel google optimize hasmany hasmany laravel hasmany laravel example hasmany relationship in laravel hasone hasone relationship in laravel How to create how to queue email how to use queue installing laravel intervention image laravel laravel 5 laravel 5 auth laravel 5.4 queue laravel 5.5 queue laravel 5.8 laravel 5.8 artisan command laravel 5.8 artisan console laravel 5.8 auth tutorial laravel 5.8 authentication laravel 5.8 commands laravel 5.8 crud laravel 5.8 crud example laravel 5.8 custom middleware laravel 5.8 deprecations laravel 5.8 eager loading laravel 5.8 elixir laravel 5.8 event listeners laravel 5.8 events laravel 5.8 feature laravel 5.8 features laravel 5.8 global middleware laravel 5.8 install laravel 5.8 lazy loading laravel 5.8 listeners laravel 5.8 middleware laravel 5.8 multi auth laravel 5.8 named resource routes laravel 5.8 named routes laravel 5.8 new feature laravel 5.8 own artisan command laravel 5.8 queue laravel 5.8 queues laravel 5.8 routing laravel 5.8 telescope laravel 5.8 tutorial laravel 5.8 user auth laravel 5.8 user authentication laravel 5.8 what's new laravel 5.9 laravel admin permissions laravel api laravel artisan command laravel artisan console laravel assets laravel auth laravel auth role laravel authentication laravel authorization laravel axios post example laravel background process laravel background task laravel background worker laravel beginner to master laravel belongsto laravel belongsto vs hasone laravel belongstomany laravel best packages laravel best practices laravel best tutorial laravel bootstrap laravel command laravel command line laravel commands tutorial laravel composer install laravel connect db laravel console command laravel console testing laravel contact form send email laravel controllers laravel create laravel crud laravel crud policy laravel custom command laravel custom middleware laravel database laravel database configuration laravel database relationships laravel database seeder laravel database settings laravel db seed laravel db settings laravel debugging laravel deploy aws laravel deploy digital ocean laravel deploy on digitalocean laravel deploy on server laravel deploy to production laravel deployment laravel digitalocean laravel drag and drop file upload laravel dropzone file upload laravel dropzone image upload laravel e-commerce laravel eager loading laravel eager loading tutorial laravel eager loading with condition laravel elixir laravel eloquent laravel eloquent belongsto laravel eloquent crud laravel eloquent hasmany laravel eloquent where laravel eloquest tutorial laravel events and queue laravel events tutorial laravel factory laravel feature test laravel feature testing laravel fetching data from database laravel file storage laravel fillable example laravel flash message notification laravel for beginners laravel form validation laravel forms laravel forms bootstrap snippets laravel from scratch laravel from the ground up laravel front end laravel frontend tutorial laravel gate and policy tutorial laravel global middleware laravel hasmany laravel hasone laravel i18n laravel installation laravel installation mac laravel intervention image tutorial laravel javascript tutorial laravel jobs queue laravel language laravel language switcher laravel language tutorial laravel languages laravel lazy loading laravel listener event laravel listeners laravel localization laravel login laravel mailable tutorial laravel many to many relationship example laravel markdown email laravel markdown mail laravel mass assignment laravel middleware laravel migrate fresh laravel mix laravel mix 5.8 laravel mix vue laravel model factory tutorial laravel multiple language laravel mysql json laravel named resource routes laravel named routes laravel new features laravel news laravel nginx laravel node modules laravel npm install laravel npm run watch error laravel one to one laravel paginate laravel paginate link laravel pagination laravel pagination 5.8 laravel pagination links laravel pagination tutorial laravel phpunit laravel phpunit testing laravel pivot table example laravel policy laravel preview laravel query optimization laravel queue laravel queue event listener laravel react laravel register user laravel registration laravel registration validation laravel relationships laravel reset password laravel role middleware laravel role permission laravel roles laravel route group middleware laravel routes laravel routing laravel routing with parameters laravel sass laravel save file to database laravel scopes laravel seo tutorial laravel server laravel session data laravel ssl laravel supervisor laravel tailwind css laravel tailwind setup laravel tdd laravel tdd tutorial laravel telescope laravel telescope installation laravel telescope tutorial laravel test driven development laravel test workflow laravel testing laravel testing controllers laravel testing tutorial laravel tools laravel translation laravel tutorial laravel tutorial for beginners laravel ubuntu server laravel ubuntu tutorial laravel unit testing controllers laravel upload file laravel upload image to storage laravel upload multiple files at once laravel upload multiple image to database laravel upload multiple images laravel url slug laravel vue laravel vue js crud laravel vue setup laravel vue tutorial laravel vue.js laravel webpack error laravel webpack tutorial lazy loading lazy loading laravel lazy loading vs eager loading learn laravel learn laravel framework step by step localization in laravel localization laravel many to many laravel mvc tutorial for beginners in php mvc tutorial laravel mysql mysql relational database mysql relationship n + 1 problem n + 1 problem laravel new artisan command npm install npm run dev npm run watch laravel one to many one to one one to one laravel own artisan command pagination pagination bootstrap pagination bootstrap php mysql pagination laravel pagination laravel bootstrap pagination links pagination php php php artisan php carbon immutable php framework php framework 2019 php what's new 2019 phpunit phpunit laravel phpunit testing pivot laravel policy laravel polymorphic relationships queue and events queue email queue for laravel queue jobs queue laravel 5.8 registration form relationship laravel eloquent relationship mysql restful controller role permission in laravel roles laravel route model binding laravel routing in laravel save image to database seo friendly seo friendly content writing seo friendly website seo laravel seo optimization simple pagination laravel slugify sqlite relational database sqlite relationships between tables symfony command console symfony laravel tailwind css tailwind laravel mix telescope laravel tutorial laravel unit testing unit testing laravel upload file laravel upload file php upload image laravel upload image to database php upload images laravel upload multiple files in php url slug laravel url slug php vue vue.js vuejs laravel why use laravel queue why use queue