Laravel 更新唯一列(如果存在)的规则

Laravel rule to update unique column if it exists

我有一个名为 positions 的 table,其中 user_position 是唯一编号。如果新 user_position 在 table 中不存在或等于当前 user_position,我只想更新一条记录。我如何表达这样的规则?我下面的当前规则不允许更新。

$rule=[    
    'user_position' => 'required|integer|unique:positions'
]

使用updateOrCreate()方法:

$positions = Position::updateOrCreate(
    ['user_position' => $userPosition],
    ['name' => $newName, 'age' => $newAge]
);

You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step.

https://laravel.com/docs/5.5/eloquent#other-creation-methods

可以在此处的文档中找到答案和更多详细信息https://laravel.com/docs/5.5/validation#rule-unique

所以按照文档,我的规则变成了这个

$rule=['user_position' => 'required|integer|unique:positions,id']

来自 Docs

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

这是使用必需的忽略实现此目的的方法。

如果您使用 Form Requests 进行验证,您可以这样做。假设 url 类似于 /positions/1/edit 用于编辑和 positions/create

use Illuminate\Validation\Rule;
....

public function rules()
{
    //position id
    $id = $this->route()->parameter('position'));
    //or like this if id is in parameter as 2nd segment
    //$id = $this->segment(2); 

    return [
        'user_position' => [
            'required',
            Rule::unique('positions')->ignore($id)
        ]
    ];
}

如果您没有使用请求 类 进行验证

 //get id of parameter positions
 //using Illuminate\Http\Request $request;
 $id = $request->route()->parameter('position'));
 //or using helper
 // $id = request()->route()->parameter('position'));

 $rule=[ 
     'user_position' => [
           'required',
           Rule::unique('positions')->ignore($id)
      ]
 ];