Maybe I am doing this wrong... here is the scenario. I have a form that saves a User. A user can belong to many distribution lists. I have a multi-select box to show which lists a user belongs to. When I save the form I want to destroy all the lists the user had, and then save the ones selected in the multi-select box.
I am not sure how to easily grab all the ids of the related distribution list.
I know I can loop through the model and add the IDs to an array but is there a better way to save these?
User model
public function distlist() {
return $this->belongsToMany('Distlist', 'user_distlist', 'user_id', 'distlist_id');
}
On Save
//get current related IDs for removal
$cur_ids = array();
foreach($user->distlist as $list){
$cur_ids[] = $list->id;
}
//detach IDs
$user->distlist()->detach($cur_ids);
//add new IDs
$user->distlist()->attach(Input::get('dist_list_id'));
This works fine, but it feels like there should be a better way to "detach all" without looping and building that array, or even a better way to get all the related IDs without the loop?
Haha duh!!
Not sure why I was convinced I had to pass an ID... I guess I needed some sleep. Thanks so much!!
I believe sync does exactly what you're doing: http://laravel.com/docs/4.2/eloquent#inserting-related-models
Using Sync To Attach Many To Many Models
You may also use the sync method to attach related models. The sync method accepts an array of IDs to place on the pivot table. After this operation is complete, only the IDs in the array will be on the intermediate table for the model:
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community