How do I reload a relation collection in laravel?
PhpCollectionsLaravelLaravel 4RelationshipPhp Problem Overview
In laravel, after using attach() or detach() to add or remove something from a relation, the collection has not changed. So if I have a model whose realation contains [1, 2]
, after this:
$model->relation()->detach(1);
$model->relation()->attach(3);
it will still contain [1, 2]
! How do I refresh it?
Php Solutions
Solution 1 - Php
You can easily tell laravel to load a relation with a single command:
$model->load('relation');
Will tell it to refresh the relation collection, and $model->relation
will now show the correct values.
Also unloading a relation will be like this:
$model->unsetRelation('relation')
Solution 2 - Php
either just unset
it and let the system reload on demand.
unset($model->relation)
or
$model->unsetRelation('relation');
And let it be loaded on request.
Solution 3 - Php
Conclusion: three solutions in here
$model->load('relation');
unset($model->relation);
$freshCollection = $user->roles()->get();`
Solution 4 - Php
It is possible to use Eloquent query builder:
$freshCollection = $user->roles()->get();
Solution 5 - Php
If you want to force all your relations to reload on an as-needed basis and you're inside your model, you can use:
$this->relations = [];
Solution 6 - Php
From Laravel 7.x you can use $model->refresh()
for refreshing the model and it's relations.
Solution 7 - Php
$model->fresh() did the job for me. Wanted to replicate multiple levels of nested models then do a loop over them. Laravel was caching the previous relation and not the new "current" relation.