4

Let's say I have a collection with categories, while eager loading all descriptiones per category. So this means, each category hasMany descriptions. I want to display all descriptions in a dropdown, while the optgroup label is the category name, belonging to the description. So something like this:

{{ Form::select('description', ['' => 'Select'] + $descriptions) }}

And the results will be something like this (first google hit):

Example

I know I need to simply pass a multidimensional array, but I am not sure how to achieve that. Any pointers would be helpful. I know the following will give me an array of Categories:

Category::orderBy('name', 'asc')->pluck('name', 'id')->all();

But I cannot simply load the descriptions, since the following will produce the same attay, without any descriptions:

Category::with('descriptions')->orderBy('name', 'asc')->pluck('name', 'id')->all();
Hardist
  • 2,098
  • 11
  • 49
  • 85

1 Answers1

2

Load categories:

$categories = Category::with('descriptions')->orderBy('name', 'asc')->get();

Then prepare the $descriptions array:

foreach ($categories as $category) {
    $descriptions[$category->name] = $category->descriptions->pluck('name', 'id');
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • This would simply create multiple dropdowns, wouldn't it? But I need everything in one dropdown, with the category names being an optgroup label – Hardist Jan 10 '18 at 14:01
  • @Hardist yes, since you have many categories. If you want to display all the descriptions in one dropdown, use the code from the updated answer. – Alexey Mezenin Jan 10 '18 at 14:05
  • Apologies, I know how to display a simple dropdown using a collection. But I want to display the category names as optgroup label, and for each optgroup (category) I want to display the description names. Right now I am doing it using a lot of foreach loops, but I don't want that – Hardist Jan 10 '18 at 14:09
  • Seems to go in the right direction, but I cannot figure out how to display the data how I want in a dropdown. Any thoughts? – Hardist Jan 10 '18 at 15:13
  • 1
    @Hardist as far as I remember, you should just put the array with this format `['group' => ['key' => 'item', 'key' => 'item']]` and Laravel Collective Form will build the dropdown with groups. – Alexey Mezenin Jan 10 '18 at 15:44
  • 1
    Thanks, will play around with it :) Much appreciated – Hardist Jan 10 '18 at 17:33
  • Just came back to this question using google lol. Needed it again. Don't remember what I did last time, but this time I just added `->toArray()` like so: `foreach ($categories as $category) { $descriptions[$category->name] = $category->descriptions->pluck('name', 'id')->toArray(); }` And that worked :) – Hardist Jul 17 '18 at 17:57