Search code examples
phparrayslaravelselectoptgroup

Laravel Form dropdown with optgroup


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();

Solution

  • 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');
    }