【问题标题】:Validate single rows only when they are present Laravel仅在存在时验证单行 Laravel
【发布时间】:2014-03-17 21:32:52
【问题描述】:

所以我有一个名为 Customer 的模型。 Customer 的 db 如下所示:

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 在某些字段上是必需的,因此当它不存在时,我无法更新该单行。没有收到其他字段(我不发布的女巫)是必需的错误。

我将如何最好地解决这个问题?

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    我想出了另一个解决这个问题的方法,效果很好,而且更干净。

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

    【讨论】:

      【解决方案2】:

      您应该获得代表您要编辑的行的模型实例,这就是为什么资源控制器的更新方法有一个参数是您要编辑的资源。

      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;
      

      【讨论】:

      • 这是一个聪明的主意。谢谢我试试那个
      • 问题在于它看起来很糟糕,而且我并没有真正更新一行。它虽然有效。
      • @oBo 资源控制器的编辑应该只更改控制器所代表的模型的一个实例。如果您想编辑更多内容,请创建一个新函数并传递您要编辑的那些行,然后您可以在循环中验证每一行。
      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 2022-01-04
      • 2019-06-12
      • 1970-01-01
      • 2020-04-26
      • 2014-01-30
      • 1970-01-01
      • 2017-10-13
      相关资源
      最近更新 更多