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
you need to set its default value to null in its migration file.
$table->integer('idExternal')->nullable()->default(NULL);
if the column is nullable like mentioned in your OP ;) then simply LEAVE IT OFF the query..
@BezhanSalleh : yes, the default is set to null
@shez1983 : I've something like 'idExternal' => ($test) ? $test : NULL so, I can't.
thanks
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
if the default is set to null then ($test) ? $test : NULL; will work fine.
Strange. When I test this it saves null just fine.
Maybe ($test) is always returning true?
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]
@aboozar_k please, create new thread and do not hijack a 5 year old one
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 sign in or create an account to participate in this conversation.