How do I reload a relation collection in laravel?

PhpCollectionsLaravelLaravel 4Relationship

Php 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.

Here the docs

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenubirdView Question on Stackoverflow
Solution 1 - PhpBenubirdView Answer on Stackoverflow
Solution 2 - PhpYevgeniy AfanasyevView Answer on Stackoverflow
Solution 3 - PhpkevinYangView Answer on Stackoverflow
Solution 4 - PhpJames AkwuhView Answer on Stackoverflow
Solution 5 - PhpSabrina LeggettView Answer on Stackoverflow
Solution 6 - PhpGiuse PetrosoView Answer on Stackoverflow
Solution 7 - PhpLiam MitchellView Answer on Stackoverflow