How do I reload a relation collection in laravel?

Benubird picture Benubird · Apr 29, 2014 · Viewed 28k times · Source

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?

Answer

Benubird picture Benubird · Apr 29, 2014

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')