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?
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.
In this case i like to use mutators :
public function setTargetAttribute($target){
$this->attributes['target'] = $target ?: null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With