该用getCastType而非castAttribute时,是当需将数据库字段(如JSON字符串)转为只读不可变对象(如Money、PhoneNumber),且不参与写回数据库;此时应优先使用getCastType+自定义Cast类,避免绕过Laravel的Cast生命周期管理。

什么时候该用 getCastType 而不是 castAttribute
当你需要把数据库字段(比如 JSON 字符串)转成一个不可变的自定义对象(如 Money、PhoneNumber、CarbonPeriod),且这个对象在模型生命周期中只读、不参与写回数据库时,优先走 getCastType + 自定义 Cast 类的方式。直接重写 castAttribute 容易漏掉反向转换(set 逻辑),也绕过了 Laravel 的 Cast 生命周期管理。
常见错误现象:setAttribute('price', new Money(100)) 后保存失败,或取出来是数组/字符串而非对象——说明没实现 set 方法或没注册 Cast。
-
getCastType只控制读取(get),适合纯展示型封装 - 完整双向转换必须实现
Illuminate\Contracts\Database\Eloquent\CastsAttributes接口,含get和set两个方法 - Laravel 9+ 推荐用
castUsing在模型中声明,而非全局$casts数组里写类名字符串
如何写一个安全的 Money 自定义 Cast
以将数据库中的 price_cents(整数)转为 Money 对象为例,关键点在于:避免空值崩、兼容 null/0、明确单位、不意外修改原始属性。
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
<p>class MoneyCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
if ($value === null) {
return null;
}</p><pre class="brush:php;toolbar:false;"> return new Money((int) $value, 'USD'); // 假设用 moneyphp/money
}
public function set($model, string $key, $value, array $attributes)
{
if ($value === null) {
return [$key => null];
}
if ($value instanceof Money) {
return [$key => $value->getAmount()]; // 写回 cents 整数
}
// 兜底:允许传入 int(cents)、float(dollars)、string("19.99")
$cents = is_numeric($value)
? (int) round((float) $value * 100)
: 0;
return [$key => $cents];
}}
- 不要在
get里做副作用操作(如日志、DB 查询)——Cast 应无状态 -
set必须返回键值对数组,不能只返回值;否则 Laravel 不知道要赋给哪个字段 - 若字段是
price(存 dollars)而非price_cents,需调整单位换算逻辑,但建议数据库统一存整数 cents 避免浮点误差
$casts 数组 vs castUsing:为什么推荐后者
在模型里写 protected $casts = ['price_cents' => MoneyCast::class] 看似简单,但会丢失依赖注入能力,也无法传参(比如不同货币)。而 castUsing 支持闭包或带参数的类实例化:
protected function casts(): array
{
return [
'price_cents' => MoneyCast::class,
'balance_cents' => MoneyCast::class, // 复用没问题
'tax_amount' => fn() => new MoneyCast('EUR'), // 传参构造
];
}
-
$casts数组只支持类名字符串,Laravel 用new $class实例化,无法传参 -
castUsing(Laravel 9.2+)返回闭包或对象,可注入服务、读配置、区分上下文 - 若用旧版 Laravel,可用
protected $casts = ['price_cents' => MoneyCast::class],但 Cast 类内部需自行处理多货币逻辑(如查用户偏好)
调试 Cast 不生效的三个检查点
写了 Cast 却发现属性还是数组或字符串?先盯住这三处:
- 模型是否用了
protected $casts或casts(),且键名和数据库字段名**完全一致**(包括下划线/驼峰) - 自定义 Cast 类是否真的实现了
CastsAttributes接口,且get/set方法签名正确(参数顺序、返回类型) - 是否在模型已加载后才修改 Cast?Eloquent 不会动态重载 Cast,需重启队列 worker 或清除 config cache(
php artisan config:clear)
最常被忽略的是:Cast 只对 getAttribute(如 $user->price_cents)和 setAttribute 生效,对 $model->getOriginal('price_cents') 或 $model->toArray() 中的原始值无效——那是未经过 Cast 的 raw 数据。











