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

stepassia's avatar

Insert null value with query builder

Hi, I've this query:

$id = DB::table('table1')->insertGetId([
    'id'          => $request->input('id'), 
    'idExternal'  => NULL
]);

The query executed is like this one:

INSERT into 'table1' ('id', 'idExternal') values ('1', '')

The idExternal is a foreing key so, I can't write an empty value (like '') but I need to write NULL (the column is nullable).

Why the query builder convert NULL to ''? Thanks Stefano

0 likes
10 replies
BezhanSalleh's avatar

you need to set its default value to null in its migration file.

    $table->integer('idExternal')->nullable()->default(NULL);
shez1983's avatar

if the column is nullable like mentioned in your OP ;) then simply LEAVE IT OFF the query..

shez1983's avatar

then a simplish solution would be something like

$array = ['id' => $request->id];

foreach ($whatever as $s) { 

if ( $s->attribute exists) {
   $array['attribute'] = attribute;

then use that array in there.. if its really two values/attributes like your example, i would create the array by hand instead of a foreach ie just use the if inside the foreach

BezhanSalleh's avatar

if the default is set to null then ($test) ? $test : NULL; will work fine.

Snapey's avatar

Strange. When I test this it saves null just fine.

aboozar_k's avatar

hi.

I try insert NULL value in to mysql table

But some things wrong:

  • 1- in migration set nullable() method.

  • 2- in validation not set required But set integer or another conditions that means if not set => is OK and if set just integer.

  • 3- set value null in to insert column.

    I hope help another:

    my email: [email protected]

CosminComan's avatar

It may be an old thread but if someone comes upon this, the issue I had was that the DB considers NULL a string, opposed to null.

For me just changing NULL to null fixed it, for some weird reason?

Please or to participate in this conversation.