Laravel模型通过$casts、访问器/修改器和自定义Cast类实现属性类型转换。$casts用于基础类型映射,如布尔、数组、日期等,读写时自动转换;访问器和修改器适用于复杂逻辑或虚拟属性,支持字段读取和赋值时的自定义处理;自定义Cast类则适合跨模型复用的复杂转换,如金额分与元的转换。底层由Eloquent的getAttributeFromArray和setAttribute方法驱动,结合Cast管理器调用对应类型处理器。优先使用$casts处理简单类型,访问器/修改器用于依赖多字段或特定模型的逻辑,自定义Cast类则提升复用性与可维护性。需注意数据类型匹配、NULL处理、时间格式、优先级冲突及性能问题,避免序列化时的额外开销。

Laravel模型属性的类型转换,核心上是通过Eloquent提供的几种机制来完成的,主要包括
$casts
Laravel模型属性的类型转换可以通过以下几种主要方式实现,每种方式都有其适用场景和优势:
使用 $casts
$casts
class User extends Model
{
protected $casts = [
'is_admin' => 'boolean', // 将 tinyint(1) 转换为布尔值
'options' => 'array', // 将 JSON 字符串转换为 PHP 数组
'settings' => 'json', // 另一种将 JSON 字符串转换为 PHP 数组/对象的方式
'email_verified_at' => 'datetime', // 将时间戳或日期字符串转换为 Carbon 实例
'price' => 'float', // 将 decimal/string 转换为浮点数
'meta_data' => 'collection', // 将 JSON 字符串转换为 Laravel Collection
];
}当从数据库读取
User
is_admin
true
false
options
settings
email_verified_at
Carbon
使用访问器 (Accessors) 和修改器 (Mutators): 当
$casts
get{AttributeName}Attributeset{AttributeName}Attributeclass User extends Model
{
// 访问器:获取全名
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
// 修改器:保存时将名字首字母大写
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = ucfirst($value);
}
}这里
full_name
first_name
使用自定义 Cast 类: 对于需要跨多个模型复用,或者逻辑非常复杂的类型转换,自定义 Cast 类是最佳选择。它允许你将转换逻辑封装在一个独立的类中。
首先,创建一个 Cast 类,实现
CastsAttributes
// 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 $model, string $key, mixed $value, array $attributes): mixed
{
// 从数据库读取时,将分(整数)转换为元(浮点数)
return $value / 100;
}
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
// 保存到数据库时,将元(浮点数)转换为分(整数)
return (int) ($value * 100);
}
}然后在模型中使用它:
class Product extends Model
{
protected $casts = [
'price' => MoneyCast::class, // 使用自定义 Cast 类
];
}这样,无论何时访问
Product
price
Laravel模型实现自动类型转换,其核心在于Eloquent ORM的事件监听和属性处理机制。当我们谈论自动转换,通常是指通过
$casts
简单来说,当Eloquent从数据库中取出一条记录,并将其实例化为模型对象时,它会检查该模型是否定义了
$casts
$casts
'is_admin' => 'boolean'
0
1
false
true
'datetime'
'2023-10-27 10:00:00'
Carbon
织梦最新内核开发的模板,518源码论坛亲自开发,转载请备注出处。该模板属于企业通用类、机械轴承、分条机类等设备类企业都可使用,这款模板使用范围极广,不仅仅局限于一类型的企业,你只需要把图片和产品内容换成你的,颜色都可以修改,改完让你耳目一新的感觉!自带最新的手机移动端,同一个后台,数据即时同步,简单适用!
145
这个过程主要发生在
Illuminate\Database\Eloquent\Model
getAttributeFromArray
setAttribute
getAttributeFromArray
setAttribute
对于更深层次的理解,
$casts
int
float
boolean
string
array
json
object
collection
date
datetime
timestamp
$casts
get
set
我个人觉得,这种设计非常优雅。它把数据存储层和应用逻辑层之间的“翻译”工作自动化了,避免了我们在每次使用某个字段时都手动去
json_decode()
new Carbon()
这是一个很常见的选择困境,我在实际项目中也经常需要权衡。我的经验是,它们各有最适合的场景,理解这些场景能帮助你做出更好的决策。
访问器和修改器 (Accessors & Mutators) 的适用场景:
$casts
first_name
last_name
full_name
password
discounted_price
original_price
discount_percentage
is_active
status
expires_at
自定义Cast类 的适用场景:
MoneyCast
EncryptedStringCast
AddressCast
MoneyCast
get
set
Address
Currency
总结一下我的看法: 当转换逻辑简单、普适,且不依赖其他字段时,
$casts
在模型属性转换上,虽然Laravel提供了极大的便利,但确实有一些常见的陷阱和值得注意的性能考量。我个人在项目中也踩过一些坑,所以分享一下经验。
常见陷阱:
cast
int
float
price
'N/A'
cast
float
cast
array
json
NULL
[]
NULL
$casts
date
datetime
timestamp
Carbon
created_at
updated_at
$casts
$casts
$casts
$casts
$casts
get
set
get
set
set(get(value))
value
性能考量:
cast
boolean
WHERE is_admin = 1
WHERE is_admin = true
$model->toArray()
$casts
get
cast
string
cast
string
总的来说,在使用属性转换时,我们应该权衡便利性和潜在的性能影响。对于大部分场景,
$casts
以上就是Laravel模型属性转换?属性类型如何转换?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号