First, Lets understand why eager loading come in to existence! To understand nature of this problem, I am taking an example of below Laravel code.
$users = User::take(5)->get();
it will fire query in MySql that is:
SELECT * FROM users LIMIT 5;
Now for example, User model is associated with Department model in many-to-one relationship.
class Department extends Model{ public function users(){ return $this->hasMany('App\User'); } }
And User model is related to Department with belongs-to association.
class User extends Model{ public function department(){ return $this->belongsTo('App\Department'); } }
Now to display department for each user we normally write code this way.
<ul> @foreach($users as $user) <li>{{$user->state()->name}} </li> @endforeach </ul>
Problem here is, initial query and ensuring iteration results in the execution of 6 queries! Thus the name “N + 1”, because we’re executing one query to retrieve the five users, and then five additional queries to retrieve the name of each user’s department!
We can inform Laravel to preload data using with() to minimize DB interaction and still gets same output.
$users = User::with('department')->take(5)->get();