Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel treating decimal as string

Im trying to make the next eloquent query

$result = $result->where('money','>=',(float)$moneyFilter);

The money column in my database its DECIMAL(11,2), when I run the query it returns an empty array, when I go over php artisan tinker and see the column money, it's a string value "11.1".

I would like to filter the $result collection to have values over $moneyFilter.

Thanks

like image 816
alexalejandroem Avatar asked Jul 14 '17 08:07

alexalejandroem


1 Answers

You need to define in your model which fields need to be cast to a primitive attribute.

  protected $casts = ['my_decimal' => 'float'];

There is a really good explanation here:

https://mattstauffer.com/blog/laravel-5.0-eloquent-attribute-casting/

Also there is an explanation in the docs:

https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting

like image 193
Mahdi Younesi Avatar answered Oct 28 '22 14:10

Mahdi Younesi