Laravel/FilamentPHP中Money Cast在资源提示文本失效问题求助
问题分析与修复方案
问题原因
- MoneyCast类型不匹配:你的
MoneyCast类中set方法返回float类型,但数据库salary字段应为整数类型。虽然Laravel会自动转换类型存储,但这种不一致可能导致模型内部属性状态异常,影响Filament闭包中的取值判断。 - Tooltip未做格式化处理:仅给表格列添加了
->currency('USD')格式化,但tooltip文本直接使用原始浮点值,未做货币格式转换。
修复步骤
1. 修正MoneyCast的set方法返回类型
将set方法返回类型改为int,确保存入数据库的是整数,避免类型不一致引发的异常:
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 { return round(floatval($value) / 100, precision: 2); } public function set($model, string $key, $value, array $attributes): int { return (int) round(floatval($value) * 100); } }
2. 修正Filament表格列的闭包逻辑
确保闭包中使用经过Cast转换后的属性,并对tooltip文本做货币格式化:
use Filament\Support\Helpers\CurrencyFormatter; 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 ' . CurrencyFormatter::format($record->salary, 'USD') : ''),
如果不想依赖Filament工具类,也可以用Laravel原生方法:
->tooltip(static fn (Employee $record) => $record->salary > 500 ? 'High salary $' . number_format($record->salary, 2) : ''),
3. 验证数据库字段类型
确保数据库salary字段为整数类型(如INT或BIGINT),避免浮点型字段带来的精度问题。
内容的提问来源于stack exchange,提问作者mstdmstd
相关产品推荐
相关产品推荐

