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
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 useload
.Examples:
Collection of users:
or:
Single user:
or
Methods implementation in Laravel
Also you can look at
with
method implementation:so it's starting new query so in fact it won't execute the query until you use
get
,first
and so on where isload
implementation is like this:so it's returning the same object, but it load relationship for this object.