hretic
hretic

Reputation: 1085

laravel orm : not converting null values to column default value of column type in 5.4 version

i used to work with laravel 5.2 now i've upgraded to 5.4 i usually use my validation to pupolate object befor sending it to database like

$validation_rules  = ['title'=>'required' , 'number'=>'present|int'];
// do validation 

$obj = new Object();
foreach($validation_rules as $k=>$v )
$obj->$k = $request->input($k);

now if the user doesnt send the number parameter it would be null or false in the nnumer property of my object ... in the older versions it would automaticly change to default value of that column ... for example if i have number column type as int when inserting this object the number column would be 0

but now this doesnt happen instead im getting this error

 Integrity constraint violation: 1048 Column 'number' cannot be null

btw strict mode is off

pleas note i know all about nullable , i dont want to make those fields nullable thats the whole point... its about automatically converting null values to the default column type value when field is not nullable

Upvotes: 0

Views: 1833

Answers (2)

EddyTheDove
EddyTheDove

Reputation: 13259

In Laravel 5.4 the concept of ->default(0) is different than from Laravel 5.2. In 5.4, the default only works if you don't pass anything, so when you do

$obj->$k = $request->input($k);

if $request->input($k) is null, you are sort of 'inserting' null into a column that is not nullable, which causes the error.

So it seems you have to make the column nullable in the DB and do a check in your controller:

$obj->$k = $request->input($k) ? $request->input($k) : 0;

Upvotes: 3

ayip
ayip

Reputation: 2543

Make sure your column 'number' is nullable. If you are using Laravel migrations to create your table, you will need to add it as $table->integer('number')->nullable();

Upvotes: -1

Related Questions