0
votes

I have a model class on which I have an "overriden" ModelClass::create method in order to set some fields programmatically, however for some reason when I provide a modified array it just returns the db error "Field 'column_name' doesn't have a default value.

Following this SO answer: https://stackoverflow.com/a/19404253/3168237

I set the user class to the following:

public static function create(array $attributes = [])
{
    $attributes['username']  = SomeOtherStaticClass::generaterName ();
    $attributes['column1']   = SomeOtherStaticClass::generateValue ();
    $attributes['column2']   = $attributes['username'];

    $model = static::query()->create($attributes);

    return $model;
}

all 3 fields are in the $fillable array

And it works great. I can just run User::create()

However, I have this other model class: with its overriden create method.

public static function create(array $attributes = [])
{
    $attributes = array_merge(['computed_element' => 1 + 1], $attributes);

    $model = static::query()->create($attributes);

    return $model;
}

Unlike the User model, when I call OtherModel::create(['fillableColA', 'fillableColB]) I get the error "Field 'computed_element' doesn't have a default value". Then listing the SQL Query acknowledging 'fillableColumnA' and 'fillableColumnB' but still saying as if no 'computed_element' provided.

The fillable property of the model is protected $fillable = ['fillableColA', 'fillableColB']; (The computed_element not included).

And even though, true, migration does not have a default value for the 'computed_element' row. Neither does the UserModel class.

Why is this going on? My only guess being it's the change of the $attributes array, but again, it's just an array, isn't it?

1
That error means that you are not setting not nullable field . And to be honest such override seems quite wrong (4 years old answer).. There are laravel.com/docs/8.x/eloquent-mutators for customising what do you set overSvetoslav
Thank you for the pointer! Didn't really know about mutators. However that would still force the method call to be provided with a value for it to be set, even if its an empty value (that is, a key with a null value) wouldn't it?Lennin Marte

1 Answers

1
votes

After asking the question had to try and poke around just some more, and turns out that every field being set through the $model = static::query ()->create ($attributes); has to be in the fillable (or guarded) array, doesn't matter if its internally used or not.

My mistake for not realizing this sooner. For, of course, it IS just an array, being passed to the parent class static function that actually uses the $fillable array as if it was being used from the outside.