仅当存在Laravel时才验证单行

时间:2014-02-18 08:56:10

标签: laravel laravel-4

所以我有一个名为Customer的模型。 客户的数据库如下所示:

  

id,姓名,姓氏,个人,地址,邮编,位置,电话,电子邮件updated_at,created_at

电子邮件和电话是特殊行,因为它们存储为json对象示例

['john@doe.com','some@othermail.com','more @ mails.com']

我使用客户模型存储验证规则和自定义消息,如

<?php
class Customer extends BaseModel
{
    public function validationRules()
    {
        return array(
            'name' => 'required|max:255',
            'lastName' =>'max:255',
            'personal'=> 'integer',
            'location' => 'max:255',
            'address' => 'max:255',
            'zip' => 'required|integer',
            'phones' => 'betweenOrArray:8,10|required_without:emails',
            'emails' => 'emailOrArray'
        );
    }

    public function validationMessages()
    {
            // returns Validation Messages (its too much to write down)
    }
}

OrArray规则可在此处找到https://stackoverflow.com/a/18163546/1430587

我通过我的控制器像这样打电话给他们

public function store()
{
    $customer = new Customer;

    $messages = $customer->validationMessages();
    $rules = $customer->validationRules();

    $input['name'] = Input::get('name');
    $input['lastName'] = Input::get('lastName');
    $input['personal'] = preg_replace("/[^0-9]/", "", Input::get('personal'));
    $input['location'] = Input::get('location');
    $input['address'] = Input::get('address');
    $input['zip'] = Input::get('zip');
    $input['emails'] = Input::get('emails');
    $input['phones'] = Input::get('phones');

    foreach($input['phones'] as $i => $value)
    {
        $input['phones'][$i] = preg_replace("/[^0-9]/", "", $value);
    }


    $validator = Validator::make($input, $rules, $messages);
}

这一切都很好,但我希望能够PUT / PATCH请求更新单行。 但是validationRules在某些字段上具有Required,所以当它不存在时我无法更新该行。没有得到错误,其他字段(我不发布)是必需的。

我最好如何做到这一点?

2 个答案:

答案 0 :(得分:1)

您应该获取代表您要编辑的行的模型实例,这就是资源控制器的update方法具有您要编辑的资源的参数的原因。

public function update($resourceId) {
    $customer = Customer::where('id', '=', $resourceId);
}

现在,此客户拥有您之前设置的所有属性,因此您可以访问它们,如:

$customer->name;
$customer->lastName;

因此,当您对值进行验证时,您可以使用验证器中输入为空的现有值:

$input['name'] = (Input::get('name')) ? (Input::get('name')) : $customer->name;

或者是elvis运营商提供的更漂亮的解决方案:

$input['name'] = (Input::get('name')) ?: $customer->name;

答案 1 :(得分:0)

我提出了另一个解决这个问题的方法,该问题非常有效且更清洁。

$customer = Customer::find($id);
$input = Input::except('_method', '_token');

$customer->fill($input);
相关问题