Laravel 如果 ID 不在请求中,则进行唯一验证

Laravel unique validation if ID isn't in request

我想对一个字段做一些验证。现在适用于唯一值,问题是在更新时我得到了同样的错误。所以我想过滤请求,如果那个 post 请求包含 ID 字段那么这个字段不应该是唯一的。

public function rules()
{
    return [
        'customer_id' => 'required|unique:customers',
    ];
}

更新方法可以使用规则class'独特的方法


public function rules()
{
    return [
        'customer_id' => [
            'required',
            Rule::unique('customers')->ignore($customer->customer_id),
    ];
}

Laravel 文档:https://laravel.com/docs/8.x/validation#rule-unique

对于普通的 rules() 函数,可以这样来完成

use Illuminate\Validation\Rule;

class CustomerController extends Controller
{

    protected function rules($customer)
    {
        return [
            'customer_id' => [
                'required',
                Rule::unique('customers')->ignore($customer->exists ? $customer->customer_id : null),
        ];
    }

    public function store(Request $request)
    {
        $customer = new Customer;
        $request->validate($this->rules($customer));
    }

    public function update(Request $request, Customer $customer)
    {
        $request->validate($this->rules($customer);
    }
}

In my case I have a single method for store/update and I check If I have an ID or not. Also I added $customer = request()->all(); and ignore($customer['ID'] , that is for my specific case.

Laravel 文档警告不要将用户控制器请求输入传递​​给忽略方法

对于您的具体情况,您可以这样做

$customer = !empty($request->input('ID') ? Customer::findOrFail($request->input('ID')) : new Customer;

//Then pass the customer to the rules()
$validated = $request->validate($this->rules($customer));