Home > Software design >  Laravel - Saving INT to database turns negative
Laravel - Saving INT to database turns negative

Time:09-23

I'm saving some data to my database but there is one field which becomes negative when I save the data.

["invoice_id"]=> int(20210126075173)

This is taken from a var_dump() and is the number that I'm trying to save. This looks completely normal but when I look into the database I get the number

-1990019803

The thing is, when I run the code on my machine, it works like it's intended and saves the number as it should but when I do this on the actual server it returns that negative number. My local database is also a clone from the live database.

"Invoice_id" is a varchar field I tried changing it to INT or BIGINT but that makes no difference.

CodePudding user response:

Why you change invoice_id from var_char field to int field? I think if it is varchar, you can add "" to save into database.

CodePudding user response:

you can do several things to prevent this from happening:

  1. make the database column a UNSIGNED INTEGER by using $table->unsignedInteger('column name');

  2. Check the value before inserting to db with a if statement ( (int) ["invoice_id"] >= 0 ) ?? ["invoice_id"] * -1

The problem of difference between your local and remote server might be related to the database server(mysql,postgrs,...) version or system locale.I have not seen this before and have no idea what is causing it.

Make sure to validate the data before inserting it into database to prevent unwanted values (which takes you to second option)

CodePudding user response:

Why are you looking to cast ["invoice_id"]=> int(20210126075173) to an int, when it seems like you're already giving it an integer?

You could try:

["invoice_id"]=> 20210126075173

or if you're casting a string to an int:

["invoice_id"]=> int() '20210126075173'

  • Related