问题
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