Home » Php » php – How do I reload a relation collection in laravel?

php – How do I reload a relation collection in laravel?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

You can easily tell laravel to do it with a single command:

$model->load('relation');

Will tell it to refresh the relation collection, and $model->relation will now show the correct values.

Answer:

It is possible to use Eloquent query builder:

$freshCollection = $user->roles()->get();

Answer:

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 = [];

Answer:

Conclusion: three solutions in here

$model->load('relation');

unset($model->relation);

$freshCollection = $user->roles()->get();`

Answer:

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.