Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel eager loading using with() vs load() after creating the parent model

I am creating a Reply model and then trying to return the object with it's owner relation. Here is the code that returns an empty object:

//file: Thread.php
//this returns an empty object !!??
public function addReply($reply)
{
    $new_reply = $this->replies()->create($reply);
    return $new_reply->with('owner');
}

However, if i swap the with() method for load() method to load the owner relation, i get the expected result. That is the reply object is returned with it's associated owner relation:

//this works
{
    $new_reply = $this->replies()->create($reply);
    return $new_reply->load('owner');
}

i don't understand why. Looking for clarifications.

Thanks, Yeasir

like image 267
Yeasir Arafat Majumder Avatar asked Dec 18 '17 12:12

Yeasir Arafat Majumder


1 Answers

This is because you should use with when you don't have object yet (you are making query), and when you already have an object you should use load.

Examples:

Collection of users:

$users = User::with('profile')->get();

or:

$users = User::all();
$users->load('profile');

Single user:

$user = User::with('profile')->where('email','[email protected]')->first();

or

$user = User::where('email','[email protected]')->first();
$user->load('profile');

Methods implementation in Laravel

Also you can look at with method implementation:

public static function with($relations)
{
    return (new static)->newQuery()->with(
        is_string($relations) ? func_get_args() : $relations
    );
}

so it's starting new query so in fact it won't execute the query until you use get, first and so on where is load implementation is like this:

public function load($relations)
{
    $query = $this->newQuery()->with(
        is_string($relations) ? func_get_args() : $relations
    );

    $query->eagerLoadRelations([$this]);

    return $this;
}

so it's returning the same object, but it load relationship for this object.

like image 84
Marcin Nabiałek Avatar answered Oct 10 '22 10:10

Marcin Nabiałek