user866933
user866933

Reputation: 335

Update with default values for non nullable fields

There is a field in my table sample, which has a default, but this field won't accept NULL value.

When i update my form, and if i leave those field empty

$model->update($request->all()); 

is returning an error

Column 'sample' cannot be null (SQL: update mytable set updated_at = 2018-04-28 11:13:46, sample = , name= 'test' where id = 1)

What's the best way to update model with default values for non filled fields?

Upvotes: 0

Views: 149

Answers (3)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Use this to remove the null values from your input:

$input = array_filter($request->all(), function($value) {
    return !is_null($value);
});
$model->update($input); 

Upvotes: 0

Jaydeep Mor
Jaydeep Mor

Reputation: 1703

I think you check first your sample field get null then set default value.

if (empty($request->get('sample', null))) {
    $request->replace(['sample' => '-- Your default value --']);
}

Then,

$model->update($request->all());

Thanks.

Upvotes: 0

Salar Bahador
Salar Bahador

Reputation: 1494

You can filter $request array to get rid of empty input values with array filter function:

$model->update(array_filter($request->all())); 

Upvotes: 1

Related Questions