我正在使用Laravel Nova开发一个Web管理面板。
由于Nova是一项相当新的技术,所以我遇到了一个问题。
我现在想做的是添加一个隐藏字段或扩展或覆盖create方法。
这是我的情况。让我们保存一下,我有一个vacancy
nova资源,其中包含以下字段。
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Text::make('Title')->sortable(),
Text::make('Salary')->sortable()
// I will have another field, called created_by
];
}
很简单的。我想做的是将一个名为
created_by
的新字段添加到数据库中。然后,该字段将被当前登录的用户id
($request->user()->id
)自动填充。如何覆盖或扩展Nova的创建功能?我该如何实现?
I can use resource event, but how can I retrieve the logged in user in the event?
最佳答案
您正在寻找的是Resource Events。
从文档中:
All Nova operations use the typical save, delete, forceDelete, restore Eloquent methods you are familiar with. Therefore, it is easy to listen for model events triggered by Nova and react to them. The easiest approach is to simply attach a model observer to a model:
如果您不想创建一个新的可观察对象,也可以在 Eloquent 模型中创建一个
boot
方法,如下所示:public static function boot()
{
parent::boot();
static::creating(function ($vacancy) {
$vacancy->created_by = auth()->user()->id;
});
}
但是请注意,这些要比可观察的对象难追踪一些,您或 future 的下一个开发人员可能会scratch不休,想知道“created_at”属性的设置如何。
关于Laravel Nova资源扩展/覆盖create方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389551/