rawilk / laravel-form-components

Form components built for Tailwind & Livewire.
https://randallwilk.dev/docs/laravel-form-components
MIT License
396 stars 44 forks source link

Custom Select component is causing problems in numeric array. #15

Closed mertasan closed 3 years ago

mertasan commented 3 years ago
<x-custom-select wire:model="product.category_id" :options="$categoryList"/>

This is how I get the category list:

$categoryList = $category->getCategoryTree()->pluck('name', 'id')->all();
dd($categoryList);

Output:

array:5 [▼
  1 => "Test Category"
  2 => "Test Category 2"
  3 => "Test Category 3"
  4 => "Test Category 4"
  5 => "Test Category 5"
]

This is the result:

screenshot 92

The reason is that array index numbers do not start from 0.

It seems to work fine if I use it like this:

$categoryList = $category->getCategoryTree()->pluck('name', 'id')
                                           ->values() // <<< reset the indexes
                                           ->all();
dd($categoryList);

Output:

array:5 [▼
  0 => "Test Category"
  1 => "Test Category 2"
  2 => "Test Category 3"
  3 => "Test Category 4"
  4 => "Test Category 5"
]

Result:

screenshot 93

Context

mertasan commented 3 years ago

Workaround (or correct usage):

$category->getCategoryTree()->map(function ($item) {
    return ['value' => $item["id"], 'text' => $item['name']];
})->all();
rawilk commented 3 years ago

This is something I don't think I'm going to focus on fixing right now, as I'm not really sure how I would in the first place. Since you can easily call ->values() on a collection to reset the indexes, or use ->map() to transform the collection like you showed in your examples, I don't see this as a high priority to resolve.

In my own projects, I'll usually map out simple values like that.

An alternative to mapping out an eloquent collection like that is to just define the value-field and text-field on the custom select.

Example:

<x-custom-select 
    wire:model="userId"
    :options="\App\Models\User::get(['id', 'name'])"
    value-field="id"
    text-field="name"
/>