当我编辑帖子时,我想删除已取消的类别。我使用同步方法,但它不起作用..
编辑 Blade
<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>
和 Controller
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');
}
有什么建议吗?
最佳答案
您应该将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 将被分离。
关于php - Laravel 5.5 编辑后无法删除类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453811/