Question

When I try to save a model with a missing attribute to a not-NULL db field, I don't want the application to be quiet about that, I want it to scream in vein. But it's being just fine with the empty strings that eloquent saves.

Why does MyModel::create([]) succeed??

No correct solution

OTHER TIPS

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;
            }
        }
    }
}

Credit: Set fields to null instead of empty value to avoid problems with nullable foreign keys

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top