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

bsmithicus's avatar

Best Way to Convert Empty String from Input to Null for DB

I've got a user reg. form with a ton of fields and most of them are nullable (alt. email, alt. phone, etc....). I notice that empty inputs translate to empty strings which is not technically null obviously and so I get:

Integrity constraint violation: column cannot be null

This seems stupid to me. Should I check and convert the values to null if they are empty or is there some option in validation that allows for empty strings? What's the best way to handle it if I should convert them to null?

0 likes
6 replies
Cronix's avatar

Check your /app/Http/Kernel.php file and see if this middleware is enabled: \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

7 likes
Nash's avatar
Nash
Best Answer
Level 20

Laravel already has a built-in middleware for converting empty strings to null (the one that @Cronix already pointed out). Your error message (column cannot be null) suggest that the specific column is NOT nullable.

2 likes
bsmithicus's avatar

@Cronix It is good to know that middleware exists, it is enabled.

@Nash Thank you! It slipped past me that columns had to be defined as nullable in my migration as well as in validation, it is working as expected now!

In case any others land here with the same oversight, this is how you define a column as nullable in your migration's Schema definitions:

$table->string('additional_email')->nullable();
1 like
actuallyakash's avatar

I've commented this middleware:

 \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

to avoid converting empty values in the inputs to null. But now it's not saving the default value I've defined in the migration.

$table->string('tags')->default('post');

Help needed.

Please or to participate in this conversation.