使用先前模型的值填充 $attributes?

Populating $attributes with values from the previous model?

我有一个涉及输入大量数据的 Laravel 项目(实际上是一个 Laravel Nova 项目)。为了节省一些时间,我想根据登录用户的最后一个条目在我的表单中预填一些字段。

我可以通过模型上的 $attributes 变量预填充字段,称为 Product,如下所示:

protected $attributes = [
  'category' => 'ABC'
];

我可以像这样在构造函数中为更多动态数据执行此操作:

function __construct() {
  $this->attributes['category'] = Str::random();
  parent::__construct();
}

但我不太确定当我想检索用户上次输入的内容时我将如何处理。例如,我想这样做:

function __construct() {
  $user = auth()->user()->id;
  $last = Product::where('created_by', $user)->latest()->first();
  $this->attributes['category'] = $last['category'] ?? null;
}

然而,这会陷入无限循环。如果我调用 $this->where('created_by' ...

也一样

有什么方法可以根据用户最后创建的 Product 设置新 Product$attributes 吗?

Nova 字段具有 resolveUsing 方法,因此在您的情况下,如果您想填充文本字段:

Text::make('Category')->resolveUsing(function () {
    return optional(auth()->user()->products()->latest()->first())->category;
})

我在 Nova Defaultable 包中找到了解决方案。

添加必要的特征后,只需将 ->defaultLast() 添加到资源字段,它将默认为上次设置的值。这也适用于非常适合我的用例的关系。