本文目录导读:

在 Laravel 中,访问器(Accessor)和修改器(Mutator)是 Eloquent 模型中非常实用的功能,它们允许您在获取或设置模型属性时对其进行格式化或转换。
访问器(Accessor)
访问器用于获取模型属性时对数据进行格式化处理。
基本用法
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 获取用户的全名
* 方法名格式:get{属性名}Attribute
*/
public function getFullNameAttribute(): string
{
return "{$this->first_name} {$this->last_name}";
}
/**
* 格式化日期
*/
public function getCreatedAtAttribute($value): string
{
return $value->format('Y-m-d H:i:s');
}
/**
* 处理 JSON 数据
*/
public function getSettingsAttribute($value): array
{
return json_decode($value, true) ?? [];
}
}
调用访问器
$user = User::find(1); // 直接访问属性(无需括号) echo $user->full_name; // "John Doe" echo $user->created_at; // "2024-01-15 10:30:00"
修改器(Mutator)
修改器用于在设置模型属性时对数据进行转换。
基本用法
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* 设置密码时自动加密
* 方法名格式:set{属性名}Attribute
*/
public function setPasswordAttribute($value): void
{
$this->attributes['password'] = bcrypt($value);
}
/**
* 设置名字时首字母大写
*/
public function setFirstNameAttribute($value): void
{
$this->attributes['first_name'] = ucfirst(strtolower($value));
}
/**
* 设置价格时保存为分(数据库存整数)
*/
public function setPriceAttribute($value): void
{
$this->attributes['price'] = (int)($value * 100);
}
}
调用修改器
$user = new User(); $user->password = 'plain-text-password'; // 存入数据库时会被自动加密 $user->first_name = 'JOHN'; // 存入数据库时会变成 "John" $user->save();
组合使用案例
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['name', 'price', 'stock'];
// 访问器:价格展示
public function getPriceAttribute($value): string
{
return '$' . number_format($value / 100, 2);
}
// 修改器:价格存储
public function setPriceAttribute($value): void
{
$this->attributes['price'] = (int)($value * 100);
}
// 访问器:处理布尔值
public function getInStockAttribute(): bool
{
return $this->stock > 0;
}
// 访问器:格式化时间
public function getUpdatedAtAttribute($value): string
{
return $value->diffForHumans();
}
}
// 使用示例
$product = new Product();
$product->name = 'Laptop';
$product->price = 999.99; // 通过修改器,数据库存储为 99999
echo $product->price; // 输出 "$999.99"(通过访问器格式化)
echo $product->in_stock; // 输出 true/false
使用 $casts 属性的替代方案
对于简单的类型转换,Laravel 还提供了 $casts 属性:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $casts = [
'is_admin' => 'boolean',
'settings' => 'array',
'created_at' => 'datetime:Y-m-d',
'price' => 'decimal:2',
];
}
- 数据格式统一:确保数据在系统内以特定格式存储和展示
- 逻辑封装:将复杂的属性处理逻辑封装在模型内部
- 类型转换:自动处理类型转换(JSON、布尔值、日期等)
- 安全处理:如密码加密、敏感信息保护
- 业务规则:实现业务逻辑约束,如价格单位转换
注意事项
- 访问器不改变数据库中的实际值
- 修改器需要在赋值时明确调用
- 在
toArray()和toJson()中,访问器会默认生效(除非在$hidden中配置) - 性能考虑:避免在访问器中执行耗时操作
通过合理使用访问器和修改器,可以大大简化代码逻辑,保持数据一致性,提高代码的可维护性。