Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 343
mtmacdonald Avatar asked Jul 22 '14 08:07

mtmacdonald


2 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.

like image 152
Walid Ammar Avatar answered Oct 16 '22 07:10

Walid Ammar


In this case i like to use mutators :

public function setTargetAttribute($target){

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

}
like image 25
Pierre Avatar answered Oct 16 '22 09:10

Pierre