Eloquent / Laravel: is there a reference to an object-> load ('relation') eg. object-> defuse ('relation')?
When I update a relation eg. update parent_id to Child (Child belongs to parent, parent) and respond with a Child-> Parent object since the returned parent is still old. I think this is because the parent is already loaded at this time.
Now I want to unbind the relationship so that the new parent is fetched from the db again.
Is there a way to unload the loaded relationships? How can you lazy-load using model-> load ('relation'), can you unload it again?
Thank you so much!
You can unload relationships by disabling the magic property (at least in Laravel 5.3 and up).
Using:
unset($model->relation);
What does this work (from the Model class):
public function __unset($key)
{
unset($this->attributes[$key], $this->relations[$key]);
}
It does the same as $model->setRelations([])
but for a specific relationship (instead of unloading all relationships).
Unloading relations can be done by passing an empty array to the model
$child->setRelations([]);
when you call the model afterwards, it will be reloaded at that point.
.. in the current version (5.x), at least maybe not at the time of your question :)
There is no analog load
that allows you to unload the connection.
However, to reload the relationship from the database, you can simply call load
again
$parent = $child->load('relation');
// change parent_id
$parent = $child->load('relation');
I took a quick look at the laravel source and didn't find any hint of some kind of caching. So it just makes a new request, getting the connection again.
Thanks to @Jarek Tkaczyk for confirming my assumption
Since Laravel 5.6, there is unsetRelation(string)
.
$parent->load('child');
$parent->unsetRelation('child');
I think this provides a little more readability if you're just trying to dump one link rather than deleting everything with $parent->setRelationships([])
.