Mr.Web
Mr.Web

Reputation: 7176

Laravel casting not working on double and decimal setting to zeros

I have 2 decimal(10,8) fields on mysql with this migration:

$table->decimal('lat', 10, 8)->nullable();
$table->decimal('lng', 10, 8)->nullable();

Via an API endpoint I find the latitude and longitude.

The API returns this:

$geo->lat = 46.0081326;
$geo->lng = 8.9761892;

BUT when setting my model field like so

$estate->lat = $geo->lat;
$estate->lng = $geo->lng;

in the DB the fields gets set to 46.00000000 and 8.00000000.

Because of this I tried setting the cast in the model like so

protected $casts = ['lat' => 'double', 'lng' => 'double'];

I also tried casting to specific decimal

protected $casts = ['lat' => 'decimal:8', 'lng' => 'decimal:8'];

But no luck. I still get 46.00000000 and 8.00000000 inside the DB.

I also tried removing Laravel casts and forcing the type like this

$estate->lat = (double) $geo->lat;

But I still get empty decimal points.

These are 2 new brand new columns but I tried checking if the App has some setLatAttribute() mutator but it does not.

Upvotes: 3

Views: 6540

Answers (2)

Mr.Web
Mr.Web

Reputation: 7176

The problem was not related to the casting or typing but rather to the wrong class name.

I forgot to rename the Class name into the correct one (SmootherCommand in SmootherCommand.php) and this caused misbehaviour.

Upvotes: 0

Caleb Anthony
Caleb Anthony

Reputation: 1123

Your database is holding the data type as a decimal (which is good!), but your application tries to read that decimal as a float.

You should be able to tell your application to continue reading the data as a decimal:

protected $casts = ['lat' => 'decimal:8'];

If you're relying on Laravel's $casts functionality, you shouldn't be forcing type anywhere else in your code, this can get you into all sorts of nasty problems that are incredibly hard to debug.

Upvotes: 4

Related Questions