Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Erulezz's avatar

Eloquent structure for optgroups

I am trying the following:

I have two tables:

  • countries
  • resorts

A resort belongs to a country. The relationships are set up and working fine. In a view i want to have a dropdown selectbox with optgroups like the following:

  • Deutschland

-- Resort 1 -- Resort 2 -- Resort 3

  • Austria

-- Resort 1 -- Resort 2

etc...

I know how to do this with plain PHP but i would like to use Form::select. Currently to retrieve the resorts i do this:

$resorts = Resort::where('application_id', $this->applicationId)
            ->orderBy('name', 'asc')
            ->lists('name','id')
            ->all();

Has anybody a good example on how to do this the good way?

0 likes
1 reply
davidfaux's avatar

I've search for this solution as well a few times, the only thing I could come up with last was:

    $countries = Country::orderBy('name')->get();
    $applicationId = $this->applicationId;
    $countries->load(['resorts' => function($query) use ($applicationId) {
        $query->where('application_id', $applicationId);
    }]);

    foreach($countries as $country)
    {
        if($country->resorts)
        {
            foreach($country->resorts as $resort)
            {
                $options[$country->name][$resort->id] = $resort->name;
            }
        }
    }

Use the options array in your view

    {{ Form::select('resort_id', [null + $options], null) }}
    //Using [null + $options] is an nice way to have a blank first value in a select box

Please or to participate in this conversation.