如果出于任何目的,比如说 Feature 测试时,需要从 Laravel 模型获取 $fillable 字段,可以使用模型的 getFillable() 方法将返回所有 $fillable 列的数组。
(new User())->getFillable();
# PHP >= 8.4 不需要用括号来命名模型的实例化
new User()->getFillable();
# 使用 `app()` 获取模型
app(Model::class)->getFillable();
所以,有很多方法可以获取在模型中定义的 fillable 可填充列,上面的这些例子都做同样的事情。
另外如果要获取模型的 $casts 属性可以通过 getCasts() 方法获取。
测试用例
使用 pest 断言模型的 $fillable 和 $casts 属性进行测试。
<?php
use App\Models\Post;
it('has some attributes for post model', function () {
expect(app(Post::class))
->getFillable()
->toMatchArray([
'name', 'slug', 'category_id', 'cover', 'description', 'body', 'published_at',
])
->getCasts()
->toMatchArray([
'id' => 'int',
'published_at' => 'datetime',
'deleted_at' => 'datetime',
]);
});