编程

Laravel 11:将模型强制转换(casts)移到方法中

313 2024-02-03 00:56:00

Laravel 10 中的模型强制转换(Model casts)是通过 $casts 数组属性定义的。而在 Laravel 11 中,你可以定义 casts()方法,这就打开了在内置 caster 中的静态方法、以及为自定义 casters 定义静态方法的可能:

use App\Enums\UserOption;
use Illuminate\Database\Eloquent\Casts\AsEnumCollection;
 
// ...
 
/**
 * Get the attributes that should be cast.
 *
 * @return array<string, string>
 */
protected function casts(): array
{
    return [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'options' => AsEnumCollection::of(UserOption::class),
    ];
}

在 Laravel 10 中, casts 如下所示,你不能在定义数组属性时,调用静态方法:

protected $casts = [
    'options' => AsEnumCollection::class.':'.UserOption::class,
];

这一更新与 Laravel 10 向后兼容,你仍可以通过 $casts 属性和新增的 casts() 方法来定义强制转换。$casts 属性和 casts() 方法被合并,方法键的优先级高于 $casts 属性。

如果你想利用内置 caster 的静态方法,建议将强制转换移到方法版本。

AsEnumCollection caster 示例

伴随着通过 casts() 方法定义 casts 的更新,新增静态方法被添加到内置 casters,以便于定义 casts 强制转换:

AsCollection::using(OptionCollection::class);
AsEncryptedCollection::using(OptionCollection::class);
AsEnumArrayObject::using(OptionEnum::class);
AsEnumCollection::using(OptionEnum::class);