使用唯一字段更新 Laravel 模型

sho*_*cus 3 php validation laravel laravel-5 laravel-5.2

如果模型具有唯一字段,我将无法更新模型。我收到消息“名称已被占用”。

我的控制器:

/**
 * 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'));
}
Run Code Online (Sandbox Code Playgroud)

更新类别请求

 /**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return Category::$rules;
}
Run Code Online (Sandbox Code Playgroud)

类别模型

    /**
 * Validation rules
 *
 * @var array
 */
public static $rules = [
    'name' => 'required|unique:categories,name'
];
Run Code Online (Sandbox Code Playgroud)

我尝试将以下内容附加到我的规则中:

$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>
Run Code Online (Sandbox Code Playgroud)

Ohg*_*why 7

要从检查中排除当前模型,请将 id 作为3rd列传递。

'name' => 'required|unique:categories,name,'. $this->id
Run Code Online (Sandbox Code Playgroud)