laradev
laradev

Reputation: 918

What is the difference in accessing relation directly and using with in Laravel?

Consider following model

class User {
    public function roles()
    {
        return $this->hasMany('Roles');
    }
}

I can fetch user details as below

$user1 = User::find(1);
$user2 = User::with('roles')->find(1);

Both the above methods works same. Even without using with('roles'), I can still access roles of that particular user.

echo $user1->roles; // Outputs all the roles of that user

So, my question is what is the actual difference/advantage using with('relation') ?

Upvotes: 2

Views: 49

Answers (1)

Jerodev
Jerodev

Reputation: 33196

The with() function is used for eager loading. When loading one user this will have little impact. When you try to get the roles property, the query to get the roles for this user is executed, but only for this user.

Now consider loading a list of users from the database. When you call the roles property for each of these users, a query will be executed for every user. This is not a good way to work.
When you use the with() function, the relations are eager loaded. Wich means Laravel will load all roles in one query and assign them to the correct user objects. When you call the roles property on the user objects now, the values are already loaded an no extra database query is needed. reducing the amount of queries to 2.

Upvotes: 2

Related Questions