laravel 验证:如何在输入为空时将不需要的字段设置为“空”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24882760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:53:53  来源:igfitidea点击:

Validation: how to set a field that is not required to 'null' when input is empty

laravellaravel-4

提问by mtmacdonald

I have a validation rule that looks like this:

我有一个如下所示的验证规则:

$rules = ['target' => 'numeric'];

It's not a required field. If a value is not specified in the input (i.e. Input::get('target') == ''), I want the field to be set to NULL in the database.

这不是必填字段。如果输入中未指定值(即 Input::get('target') == ''),我希望该字段在数据库中设置为 NULL。

Currently the above rule passes, and in the absence of a numeric input, it gets set to 0 in the database.

目前上述规则通过,并且在没有数字输入的情况下,它在数据库中被设置为 0。

What's the best solution?

最好的解决办法是什么?

回答by Walid Ammar

You can set field as nullin Laravel simply by assigning nullvalue to the appropriate model attribute before calling save().

您可以null在 Laravel 中设置字段,只需null在调用save().

if(! Input::get('target') ){
    $eloquent_model->target = null;
}

$eloquent_model->save();

But if you want to insert null values in more than one model, you can create base model and inherit it by all other models.

但是如果您想在多个模型中插入空值,您可以创建基础模型并由所有其他模型继承它。

class BaseModel extends Eloquent {

    public static function boot()
    {
        parent::boot();

        static::creating(function($model) {

            static::setNullWhenEmpty($model);
            return true;

        });
    }

    private static function setNullWhenEmpty($model)
    {
        foreach ($model->toArray() as $name => $value) {
            if (empty($value)) {
            $model->{$name} = null;
            }
        }
    }
}

Now all empty fields will be set to nullautomatically and you don't have to check before save.

现在所有空字段都将设置为null自动,您无需在保存前检查。

Reference.

参考

回答by Pierre

In this case i like to use mutators :

在这种情况下,我喜欢使用 mutators :

public function setTargetAttribute($target){

  $this->attributes['target'] = $target ?: null;

}

回答by Shaunak Shukla

I don't think it's an issue of laravel, you must add tag mysql... Alter the table to add Null as default value.. Currently if you pass blank value, it'll add 0 because by default it is not NULL and shows

我不认为这是laravel的问题,您必须添加标签mysql...更改表以添加Null作为默认值..目前如果您传递空白值,它将添加0,因为默认情况下它不是NULL并且显示

Warning: #1366 Incorrect integer value: '' for column 'target' at row 1. 

Here is the query to alter..

这是要更改的查询..

ALTER TABLE `table` CHANGE `target` `target` INT( 11 ) NULL

After running above query, targetwill accept NULL value instead of 0!!

运行上述查询后,target将接受 NULL 值而不是 0!

回答by TommyZG

My solution was this (Laravel 5.2):

我的解决方案是这样的(Laravel 5.2):

//Model.php

//模型.php

public function nullIfBlank($field) {
  return trim($field) !== '' ? $field : null;
}

// your custom model that extends Model.php

// 扩展 Model.php 的自定义模型

public function setTargetAttribute($target) {
  $this->attributes['target'] = $this->nullIfBlank($target);
}

Pay attention to naming your setter (mutator) exactly as above, lowerCamelCase and magic will happen.

注意完全按照上面的方式命名你的 setter(mutator),lowerCamelCase 和魔法会发生。