Seems like your accessor is not being called at all?
Aug 12, 2022
12
Level 5
Accessor int to float
Hello,
I have an int field in a table, called: weight that stores weight in grams.
I don't want to store it as decimal in the table.
When displaying it, I want to display it as kg.
e.g. if the value is 250 display: 0.25, if it is 2500 display: 25.
I tried to use accessor in my model:
public function weight(): Attribute
{
return new Attribute(
get: fn($value) => $value / 1000,
//I also tried:
get: fn($value) => number_format($value / 1000, 2, ','),
//I also tried:
get: fn($value) => floatval($value / 1000),
);
}
All of these tries display the field as is, e.g. if the value is 250 it shows me 250 and not .25
I added this as well:
protected $casts = [
'weight' => 'float',
];
Still displays 250
I tried to display it with:
number_format($value, 2, ',')
it displays 250,00
Is there a way to do what I want?
Level 29
Make sure you have imported the correct Class
use Illuminate\Database\Eloquent\Casts\Attribute;
2 likes
Please or to participate in this conversation.