Does those "Loading and N+1" problem occurs only when using ::all() ? If I get on my "job" page (singular, that we obtain with simply the ID of the job) and write this line : "This job has been posted by the employer named : {{ $job->employer->name }}", Laravel doesn't throw me an error about Lazy Loading while I'm accessing the Employer class. Is that normal ?
This only applies to collections with more than 1 element. If it has only 1 element (as what happens when you use ::find(id) to load a specific row in database) the prevention does not apply.
@SXsoft99 the problem with your code is the fact that load() is attempting to eager load the 'employer' relationship for the entire collection of jobs. However, load() is a method meant to be called on an individual model instance or a collection of model instances, not on the query result itself. You can write this code like this. $jobs = Job::get(); $jobs->each(function ($job) { $job->load('employer'); });
Thank you very much Jeffrey, I'm working on a Laravel project at my job and doing the course when I get home, great content!
A very detailed explanation of this not very simple topic! Thanks author!
U r the master of laravel
Does those "Loading and N+1" problem occurs only when using ::all() ?
If I get on my "job" page (singular, that we obtain with simply the ID of the job) and write this line : "This job has been posted by the employer named : {{ $job->employer->name }}",
Laravel doesn't throw me an error about Lazy Loading while I'm accessing the Employer class.
Is that normal ?
This only applies to collections with more than 1 element. If it has only 1 element (as what happens when you use ::find(id) to load a specific row in database) the prevention does not apply.
I am on windows and I could not make the debug bar appear. I tried tutorials online but nothing. Is it still working?
Yes this is still working, i am working on windows too.
Had no Problems at all.
installed it via composer
using chrome atm
the best course for laravel!
i'm just copying you but in debugbar my app usage is 22mb even after using eager loading,
can anyone tell me the fix for this,
nice as always
*Me starting to get lazy
Also Me: LazyBehaviorException: Attempting to Lazing around
Hmmmm what happends when you do
$jobs= Job::get();
$jobs->load('employer');
?
@SXsoft99 the problem with your code is the fact that load() is attempting to eager load the 'employer' relationship for the entire collection of jobs. However, load() is a method meant to be called on an individual model instance or a collection of model instances, not on the query result itself.
You can write this code like this.
$jobs = Job::get();
$jobs->each(function ($job) {
$job->load('employer');
});