登录
首页 >  文章 >  php教程

PHP怎么处理Eloquent Attribute Formats属性格式_Laravel特定数据格式要求【指南】

时间:2026-05-03 12:19:00 427浏览 收藏

你在学习文章相关的知识吗?本文《PHP怎么处理Eloquent Attribute Formats属性格式_Laravel特定数据格式要求【指南】》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

$casts 比访问器更适合日期/布尔/数字格式化,因其在模型读取后、写入前自动完成类型转换,全局生效且不依赖手动调用;访问器仅读取时触发,不影响查询和批量赋值。

PHP怎么处理Eloquent Attribute Formats属性格式_Laravel特定数据格式要求【指南】

为什么 $casts 比访问器更适合日期/布尔/数字格式化

因为 $casts 在模型从数据库读取后、写入前自动完成类型转换,不依赖手动调用,且对 JSON 序列化、API 响应、toArray() 全局生效。访问器(getFooAttribute)只在读取属性时触发,且不会影响 where() 查询或批量赋值。

常见错误:用访问器处理日期格式(如 Carbon::parse($this->attributes['created_at'])->format('Y-m-d')),结果导致 created_atwhereDate('created_at', '2024-01-01') 中失效——数据库字段仍是原始字符串,而模型里存的是格式化后的字符串。

  • $casts = ['is_active' => 'boolean']:把 tinyint(1)'1' 自动转为 true,比手写 boolval() 更可靠
  • $casts = ['price' => 'decimal:2']:确保小数点后两位,但注意这仅影响 PHP 层类型,不改变数据库精度
  • $casts = ['metadata' => 'array']:自动 json_encode/json_decode,避免手动处理 JSON 字段出错

日期字段必须用 datedatetime cast,别信 Carbon 类型名

Laravel 的 $casts 不接受 'created_at' => 'Carbon' 这种写法——会静默失败,字段仍为字符串。正确方式只有 'date'(只保留年月日)、'datetime'(含时分秒)、'immutable_date' 等内置类型。

使用场景:需要在 Blade 中直接输出 {{ $post->published_at->diffForHumans() }},前提是它已是 Carbon 实例。若 cast 错误,调用 diffForHumans() 会报 Call to a member function diffForHumans() on string

  • ✅ 正确:$casts = ['published_at' => 'datetime'] → 得到 Carbon 实例
  • ❌ 错误:$casts = ['published_at' => 'Carbon']$casts = ['published_at' => 'string']
  • ⚠️ 注意:'date' 会截断时间部分,whereTime() 将无法匹配小时分钟

自定义格式(如手机号脱敏、金额千分位)该用访问器还是 Mutator

这类展示层格式化不该进 $casts,因为它们破坏数据原始性,且无法反向解析。例如把 13812345678 转成 138****5678 后,就再也无法用于发送短信了。

应该用访问器(getPhoneAttribute)提供只读格式化字段,并保留原始字段可写。同时配合 $appends 让它出现在 toArray() 中。

  • 定义:protected $appends = ['phone_formatted'];
  • 访问器:public function getPhoneFormattedAttribute() { return substr($this->phone, 0, 3) . '****' . substr($this->phone, -4); }
  • Mutator(如需写入脱敏值)要格外小心:除非业务明确要求存储脱敏数据,否则不要重写 setPhoneAttribute
  • 性能提示:访问器每次读取都执行,高频列表页建议用 SELECT CONCAT(LEFT(phone,3), '****', RIGHT(phone,4)) as phone_formatted 在查询层处理

getAttributes()toArray() 对格式化字段的行为差异

getAttributes() 返回原始数据库值(绕过所有访问器和 cast),toArray() 则应用了 $casts 和访问器(包括 $appends 字段)。调试时混淆这两者,常导致“明明写了访问器却没生效”的困惑。

典型问题:API 接口返回数据中 price_formatted 是空的,但 dd($model->price_formatted) 又能打印出来——大概率是忘了加 $appends,或者用了 getAttributes() 而非 toArray()

  • $model->getAttributes()['price'] → 原始数据库值(如 9999.99'9999.99'
  • $model->toArray()['price'] → 经 $casts 转换后的值(如 9999.99 float)
  • $model->toArray()['price_formatted'] → 仅当 price_formatted$appends 中才存在

最易被忽略的一点:$castsnull 值也强制转换,比如 'status' => 'integer' 遇到数据库 NULL,会变成 0 而非 null,可能掩盖空值逻辑。需要保持 null 语义时,得用访问器手动判断。

本篇关于《PHP怎么处理Eloquent Attribute Formats属性格式_Laravel特定数据格式要求【指南】》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>