Laravel: Eager loading

Posted by Rukmi Patel | September 18, 2017

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:


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.

        @foreach($users as $user)
            <li>{{$user->state()->name}} </li> 

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();

Add a comment

*Please complete all fields correctly

Related Blogs

Posted by Rukmi Patel | October 20, 2020
Following a Unique & Streamlined Approach to Business – iTreeni Technolabs Thrives at GoodFirms
iTreeni Technolabs is a one-stop solution service provider incepted in 2017 and based in Waterloo, Australia. It possesses a stellar clientele experience with an adequate of repertory in accouching innovative...
Posted by Rukmi Patel | December 2, 2019
iTreeni Technolabs Outshines at GoodFirms by Providing End-To-End Business Solutions
Empowering clients' business by leveraging technology-enabled solutions endows iTreeni Technolabs to tap into the list of top web development companies in Australia at GoodFirms. View iTreeni Technolabs' GoodFirms' profile to...
Posted by Rukmi Patel | April 9, 2019
Comparing Full Stack V/S MEAN Stack approach
The web and mobile app development services have stepped up to next level in last 5 years. Web and apps are all built utilizing a ‘stack’ of various technologies like...