简体   繁体   English

选择不呈现正确值的 PHP Laravel 选项

[英]PHP Laravel options of select not rendering correct values

I want to display an array of values as options inside a select using the laravel-nova syntax.我想使用 laravel-nova 语法在选择中显示一组值作为选项。 I managed to get the options rendered inside the select but the values of these options are like我设法在选择中呈现选项,但这些选项的值就像

<option value="2"></option>
<option value="1"></option>
<option value="0"></option>

what I want is the text as an value.我想要的是文本作为值。

this is what I got so far:这是我到目前为止得到的:

Select::make('Slug')->options(
   $this->selectOptions()
)


public function selectOptions()
{
    $urls = DB::table('subpages');
    $slugs = $urls->pluck('slug');

    return $slugs;
}

What am I doing wrong?我究竟做错了什么?

Make sure to get() the subpages as Illuminate\\Support\\Collection and mapWithKeys() to reformat the results.确保get()子页面为Illuminate\\Support\\CollectionmapWithKeys()以重新格式化结果。 Use toArray() to provide the format Nova assumes:使用toArray()提供 Nova 假定的格式:

private function selectOptions(): array
{
    $subpages = DB::table('subpages')->get();
    return $subpages->mapWithKeys(function ($subpage) {
        return [$subpage->slug => $subpage->slug];
    })->toArray();
}

This is how the returned result should look like:返回的结果应该是这样的:

[
    'my-article-1' => 'my-article-1',
    'my-article-2' => 'my-article-2',
    'my-article-3' => 'my-article-3',
]

I suggest using the following parameters:我建议使用以下参数:

->pluck('yourValue','yourKey');

That makes for useful labels with your values.这为您的价值观提供了有用的标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM