Lazy loading means the relationship is loaded when it is accessed.
$user = User::find(1);
$orders = $user->orders;
The orders query isn't executed until the relationship is accessed.
Advantage
It is convenient when the relationship isn't always needed.
Disadvantage
It can unintentionally create N+1 queries.
In performance-sensitive applications, I prefer explicitly deciding what relationships are needed:
User::with('orders')->find($id);
Laravel can also be configured to prevent accidental lazy loading during development, helping identify N+1 problems early.
0 comments:
Post a Comment
Thanks