PHP Laravel options of select not rendering correct values

僤鯓⒐⒋嵵緔 提交于 2019-12-08 03:12:17

问题


I want to display an array of values as options inside a select using the laravel-nova syntax. 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?


回答1:


Make sure to get() the subpages as Illuminate\Support\Collection and mapWithKeys() to reformat the results. Use toArray() to provide the format Nova assumes:

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',
]



回答2:


I suggest using the following parameters:

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

That makes for useful labels with your values.



来源:https://stackoverflow.com/questions/55632933/php-laravel-options-of-select-not-rendering-correct-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!