Reputation: 3083
Using money cast class in Laravel 10/Filamentphp 3 app in app/Casts/MoneyCast.php :
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class MoneyCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes): float
{
// Transform the integer stored in the database into a float.
return round(floatval($value) / 100, precision: 2);
}
public function set($model, string $key, $value, array $attributes): float
{
// Transform the float into an integer for storage.
return round(floatval($value) * 100);
}
}
I got valid results with model app/Models/Employee.php :
class Employee extends Model
{
protected $table = 'employees';
= [
'salary' => MoneyCast::class,
];
But using in Resource table :
Tables\Columns\TextColumn::make('salary')
->currency('USD')
->icon(static fn (Employee $record) => $record->getAttribute('salary') > 500 ? 'heroicon-o-currency-dollar' : '')
->tooltip(static fn (Employee $record) => $record->getAttribute('salary') > 500 ? 'High salary ' . $record->getAttribute('salary') : ''),
As result salary field correctly shown in table value, but invalid value in hint text :
Also condition also does not work correctly, as salary value rendered correctly...
What is wrong and that can be fixed ?
Updated block : No that did not help. Using direct access to fields istead of getAttribute
Tables\Columns\TextColumn::make('salary')
->currency('USD')
->icon(static fn (Employee $record) => $record->salary > 500 ? EmployeeHelper::getHighSalaryIcon() : '')
->tooltip(static fn (Employee $record) => $record->salary > 500 ? 'High salary ' . $record->salary : ''),
both condition in icon does not work correctly and text in hint is rendered incorectltly, without casting as money.
Upvotes: 0
Views: 454
Reputation: 180023
$record->getAttribute('salary')
bypasses the accessor, which is great for the $record->getAttribute('salary') > 500
comparison, which needs real numbers, but not so great for the resulting output.
Change:
tooltip(static fn (Employee $record) => $record->getAttribute('salary') > 500
? 'High salary ' . $record->getAttribute('salary') : ''),
to:
tooltip(static fn (Employee $record) => $record->getAttribute('salary') > 500
? 'High salary ' . $record->salary : ''),
Upvotes: 1