如何为Laravel Nova字段指定默认值?

问题描述 投票:0回答:1

我想将资源字段的默认值设置为经过身份验证的用户的id。我有一个名为Note的模型,它与GameUser具有一对多的关系。

User hasMany Note
Game hasMany Note

Note belongsTo User
Note belongsTo Game

在Laravel Nova中,我的字段显示为该注释

ID::make()->sortable(),
Text::make('Note', 'note')->onlyOnIndex(),
Textarea::make('Note', 'note')->alwaysShow(),
BelongsTo::make('Game', 'game')->hideWhenCreating()->hideWhenUpdating(),
BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating(),
DateTime::make('Created At', 'created_at')->hideWhenCreating(),
DateTime::make('Updated At', 'updated_at')->hideWhenCreating(),

因为我在Note Nova资源上引用了Game,所以当我创建Note时,game_id列将正确填充。但是,我希望user_id列是经过身份验证的用户的值。它似乎不能像这样工作,我将如何实现?

laravel relationship laravel-nova
1个回答
0
投票

如果我从BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating()行中正确理解,您正在尝试为该列设置默认值而不在表单上显示该字段?

我认为这样是不可能的。一旦使用hide函数,这些字段就不会呈现,并且永远不会随请求一起传递。我尝试了此操作,并且user_id字段从未随请求一起发送。

我认为有两种方法可以做到这一点:

在表单中显示该字段,并使用元数据设置默认值(并且可能出于很好的考虑使该字段为只读)。

BelongsTo::make('Created By', 'user', 'App\Nova\User')->withMeta([
    "belongsToId" => auth()->user()->id,
])

See this part of the Nova docs

或使用雄辩的creating事件。以下将用于您的Note模型。

public static function boot()
{
    parent::boot();
    static::creating(function($note)
    {
        $note->user_id = auth()->user()->id;
    }
);

当然,以上方法有点简单。您最好使用适当的事件侦听器。

旁注:从体系结构的角度来看,我会选择选项2。在不让最终用户参与的情况下设置默认值听起来像是Eloquent模型的工作,而不是Nova表单的工作。

© www.soinside.com 2019 - 2024. All rights reserved.