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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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.

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

What’s the best solution?

Answers:

You can set field as null in Laravel simply by assigning null value to the appropriate model attribute before calling 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 null automatically and you don’t have to check before save.

Reference.

Questions:
Answers:

In this case i like to use mutators :

public function setTargetAttribute($target){

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

}

Questions:
Answers:

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

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, target will accept NULL value instead of 0!!

Questions:
Answers:

My solution was this (Laravel 5.2):

//Model.php

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

// your custom model that extends 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.