当我编辑帖子时,我想删除已取消的类别。我使用同步方法,但它不起作用..
编辑刀片
<select class="form-control m-select2" id="m_select2_3" name="categories[]" multiple="multiple">
<optgroup label="Kategoriler">
@foreach($categories as $category)
<option value="{{$category->id}}" {{ in_array($category->id,$categoriesPost) ? 'selected' : '' }}>{{$category->category_name}}
</option>
@endforeach
</optgroup>
</select>
和控制器
public function update(StoreBlogPost $request, $id){
$post = Post::find($id);
$post->title = $request->title;
$post->caption = $request->caption;
$post->content = $request->input('content');
$post->save();
$post->categories()->sync($request->categories, false);
return redirect()->route('posts.index');
}
有什么建议吗?
答案 0 :(得分:1)
您应该将sync
的第二个参数设置为true
。
从代码中
/**
* Sync the intermediate tables with a list of IDs or collection of models.
*
* @param \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|array $ids
* @param bool $detaching
* @return array
*/
public function sync($ids, $detaching = true)
{
....
}
这意味着,$ids
中没有出现的ID将被分离。