Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

danielsachs's avatar

handle unknown null values from request

Hi, I am inserting a large table and I would like to know how I can circumvent the queryException, where if query has null in value (and column is not null), it would insert a default value.

I am not interested in changing the table's nullability. there are many table columns and I don't wan't to end up doing $table->'default' on 56 columns. I am using mass assignment with create($request->all(), question is, where in that request I can create a rule of thumb where I would be able to insert string/integer instead of null.

0 likes
4 replies
Sergiu17's avatar

Hi, use Try Catch and Database Transactions

Tray2's avatar

You can use a mutator something like this

public function setFieldAttribute($value)
    {
        if (!isset($value)) {
            $this->attributes['field'] = 'Your default value';
        } else {
            $this->attributes['field'] = $value;
        }
    }
1 like
Cronix's avatar

where if query has null in value (and column is not null), it would insert a default value

So you're against the best and most logical solution (adding default values to your migrations) because it will take awhile? The alternatives will take longer as it sounds like you're wanting to check specific fields and give them a specific value based on that field if they are null before inserting. Further you'd have to make an extra query to get the table schema to see if a column is marked as "is not null". If you're just wanting to insert empty strings for everything that is null instead of inserting null that would be easy as you'd just have to disable the ConvertEmptyStringsToNull middleware.

It really wouldn't take long to add default values to your migrations and is the proper, most efficient solution as it puts the burden on the db instead of the much slower php layer. 56 columns? You'd already be done if you started when you posted your post.

danielsachs's avatar
danielsachs
OP
Best Answer
Level 9

I ended up pacifying null attributes via an array in model and then merged in a create request for model, as follows:

$newWally = WallyConfig::create(array_merge($request->all(),
            WallyConfig::NON_WALLY_PACIFIED_COLUMNS));
        return $newWally;

NON_WALLY_PACIFIED_COLUMNS is the array that holds key/value which handles an immense number of request values (returning null), since this re-occurs it was the most relevant solution that I saw. I reckon Mutators is a fancier way of doing what I did.

Thanks for the help gentlemen.

Please or to participate in this conversation.