如果模型具有唯一字段,我将无法更新模型。我收到消息“名称已被占用”。
我的 Controller :
/**
* Update the specified Category in storage.
*
* @param int $id
* @param UpdateCategoryRequest $request
*
* @return Response
*/
public function update($id, UpdateCategoryRequest $request)
{
$category = $this->categoryRepository->findWithoutFail($id);
if (empty($category)) {
Flash::error('Category not found');
return redirect(route('categories.index'));
}
$category = $this->categoryRepository->update($request->all(), $id);
Flash::success('Category updated successfully.');
return redirect(route('categories.index'));
}
更新类别请求
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return Category::$rules;
}
类别模型
/**
* Validation rules
*
* @var array
*/
public static $rules = [
'name' => 'required|unique:categories,name'
];
我尝试将以下内容附加到我的规则中:
$this->id
$id
@include('adminlte-templates::common.errors')
<div class="box box-primary">
<div class="box-body">
<div class="row">
{!! Form::model($category, ['route' => ['categories.update', $category->id], 'method' => 'patch']) !!}
@include('categories.fields')
{!! Form::close() !!}
</div>
</div>
</div>
最佳答案
要从检查中排除当前模型,请将 ID 作为 3rd
传递柱子。
'name' => 'required|unique:categories,name,'. $this->id
关于php - 使用唯一字段更新 Laravel 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38257987/