So I have a boolean column that is nullable created in Laravel using
$table->boolean('colName')->nullable();
The issue I am having is I want to insert a null value into it.
But as far as I know, if you assign null (using Eloquent's create or update), php will evaluate null to false, thus assigning 0 (false) into the column instead.
$toInsert = null;
This doesn't work.
How I use my code
First I get the input from form
$nullableVal = $request->input('nullable-value');
if($nullableVal == "yes"){
$toInsert = true;
}else if($nullableVal == "no"){
$toInsert = false;
}else{
$toInsert = null;
}
My store/update via eloquent
$this->repository->update(['nullableVal' => $toInsert]);
Is there a way around this?
Thank you
CodePudding user response:
If the field is nullable, it's default value should be NULL, right? In that case, just remove the else case.
$model = new Model;
if ($nullableVal == "yes") {
$model->colName = true;
} elseif ($nullableVal == "no") {
$model->colName = false;
}
$model->save();
If $nullableVal is neither 'yes' or 'no', then colName won't be set and therefore, become NULL in the database.
CodePudding user response:
if migration has nullable() than by default it is already NULL in database
By default make $toInsert NULL
$nullableVal = $request->input('nullable-value');
$toInsert = NULL;
if($nullableVal == "yes"){
$toInsert = true;
}
$this->repository->update(['nullableVal' => $toInsert]);
