Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reload a relation collection in laravel?

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?

like image 580
Benubird Avatar asked Apr 29 '14 12:04

Benubird


People also ask

How many types of relations are there in Laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)

What is fillable array in Laravel?

In eloquent ORM, $fillable attribute is an array containing all those fields of table which can be filled using mass-assignment. Mass assignment refers to sending an array to the model to directly create a new record in Database.


1 Answers

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') 
like image 106
Benubird Avatar answered Sep 24 '22 02:09

Benubird