使用唯一字段更新 Laravel 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38257987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:06:56  来源:igfitidea点击:

Updating a Laravel model with a unique field

phpvalidationlaravellaravel-5laravel-5.2

提问by showFocus

I am unable to update a model, if it has a unique field. I get the message "The name has already been taken."

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

My 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'));
}

UpdateCategoryRequest

更新类别请求

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

Category Model

类别模型

    /**
 * Validation rules
 *
 * @var array
 */
public static $rules = [
    'name' => 'required|unique:categories,name'
];

I've tried appending to my rules, the following:

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

$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>

采纳答案by showFocus

Ok, so this worked for me:

好的,所以这对我有用:

In my UpdateCategoryRequest:

在我的 UpdateCategoryRequest 中:

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

回答by Ohgodwhy

To exclude the current model from the check, pass the id as the 3rdcolumn.

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

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

回答by rzb

I don't think you will be able to tackle this by retrieving your rules from the model statically without any changes, because you'll have to append the model id dynamically to the uniquerule as the third parameter.

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

To get the model id, you need access to the request, which you only have in your FormRequestclass, using $this->route('id')in your case. Or, if you are using route model bindingand you have defined your route path like my/route/{category}, then:

要获取模型 ID,您需要访问该请求,该请求仅在您的FormRequest班级中具有,并$this->route('id')在您的情况下使用。或者,如果您正在使用路由模型绑定并且您已经定义了像 一样的路由路径my/route/{category},那么:

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

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

    return $rules;
}

Unless of course you go fancy and declare a getter method in your model that will accept the id as parameter and build the rule there.

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

回答by lagbox

In your request, just append to the 'name' rule you get from the model.

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

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

回答by Anand Shrestha

Do this.

做这个。

You need to exclude current model .Since you demand unique for table it is not excluding your current column or say id.

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

Do edit your request

请编辑您的请求

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;
    }
}

回答by Anand Shrestha

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'));
}