【问题标题】:Updating a Laravel model with a unique field使用唯一字段更新 Laravel 模型
【发布时间】:2016-11-10 12:15:42
【问题描述】:

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

我的控制器:

/**
 * 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>

【问题讨论】:

  • 你能包括你的路线定义吗?
  • 试试我的更新答案。

标签: php validation laravel laravel-5 laravel-5.2


【解决方案1】:

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

'name' => 'required|unique:categories,name,'. $this->id

【讨论】:

  • 这行不通,因为 $this 不在对象上下文中时使用。但它指向了正确的方向。
【解决方案2】:

在您的请求中,只需附加到您从模型中获得的“名称”规则。

public function rules()
{
    $rules = Category::$rules;
    $rules['name'] .= ','. $this->route('id');
    return $rules;
}

【讨论】:

  • "SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where 子句'" 是我用你的代码保存时得到的结果。
【解决方案3】:

好的,这对我有用:

在我的 UpdateCategoryRequest 中:

public function rules()
    {
        $rules = Category::$rules;
        if ($this->isMethod('patch'))
        {
            $id = $this->categories;
            $rules['name'] = $rules['name'].',name,'.$id;
        }
        return $rules;
    }

【讨论】:

  • 简单来说,除非其他用户使用完全相同的数据,否则您必须将 id 作为第三个参数传递以忽略唯一检查。
【解决方案4】:

这样做。

您需要排除当前模型。由于您要求表的唯一性,因此不排除您当前的列或说 id。

请编辑您的请求

public function rules()
{
    switch($this->method())
    {
        case 'GET':
        case 'DELETE':
        {
            return [];
        }
        case 'POST':
        {
            return [
                'name' => 'required|unique:categories',

            ];
        }
        case 'PUT':
        case 'PATCH':
        {
            return [
                'name' => 'required|unique:categories,name,'.$this->getSegmentFromEnd().',id'

        }
        default:break;
    }
}

【讨论】:

  • "未定义变量:id"
  • 我认为错误来自视图而不是请求。请务必完全解释您的错误
  • 我已经添加了我的观点,如果有帮助?
  • 这里我已经通过切换案例对您的请求文件进行了更改。请查看
【解决方案5】:

我认为您无法通过在不进行任何更改的情况下静态地从模型中检索您的规则来解决此问题,因为您必须将模型 ID 作为第三个参数动态附加到 unique 规则中。

要获取模型 ID,您需要访问请求,该请求仅在您的 FormRequest 类中具有,在您的情况下使用 $this-&gt;route('id')。或者,如果您使用的是route model binding,并且您已经定义了类似my/route/{category} 的路由路径,那么:

public function rules()
{
    $category = $this->route('category');

    $rules = Category::$rules;
    $rules['name'] .= ",{$category->id}";

    return $rules;
}

当然,除非您花哨并在模型中声明一个 getter 方法,该方法将接受 id 作为参数并在那里构建规则。

【讨论】:

    【解决方案6】:
    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 = $category->update($request->all());
    
        Flash::success('Category updated successfully.');
    
        return redirect(route('categories.index'));
    }
    

    【讨论】:

    • 好的,你需要把条件放在那里。因为你已经对方法提出了单独的请求,它不会识别你的 id。我在请求页面上做了一些小改动
    • 仍然收到相同的验证错误“名称已被占用。”
    • 您是否使用了与上面显示的代码相同的代码,我的意思是 switch case。也请告诉我您的路线。
    猜你喜欢
    • 2014-05-06
    • 2018-08-09
    • 2014-12-11
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多