【问题标题】:How to perform validation when updating a unique field using Http\Request in Laravel在 Laravel 中使用 Http\Request 更新唯一字段时如何执行验证
【发布时间】:2016-03-31 20:12:05
【问题描述】:

我有一个customers 表,我使用CustomerRequest 来验证字段,通过使用rules 函数。该表有一个email 字段,它是必需的并且是唯一的。这在我创建客户时工作正常,但是当我更新客户信息时(假设我的姓氏拼写错误)我的请求失败,因为email 地址已经在数据库中。

这是我的客户请求:

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

我想为所有客户验证重复使用CustomerRequest,我该怎么做?

【问题讨论】:

    标签: php validation laravel-5.1


    【解决方案1】:

    您需要在此处检查请求类型以及客户 ID 以进行更新,然后根据请求返回规则。像这样的

    public function rules(Request $customer_request)
    {
    return [
        'givenname' => 'required',
        'surname' => 'required',
        'email' => 'required|unique:customers,email,'.$customer_request->get('customer_id'),
    ];
    }
    

    【讨论】:

    • 只是想知道:如果没有 customer_id 作为请求传递怎么办?那应该怎么解决呢?
    • 如果没有customer_id,则此请求必须用于新插入,如果找到则必须用于更新。这里 laravel 将处理 customer_id 的存在。
    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 2019-11-11
    • 2018-07-05
    • 2023-04-09
    • 1970-01-01
    • 2014-06-28
    • 2019-03-24
    • 2019-02-26
    相关资源
    最近更新 更多