Laurence
Laurence

Reputation: 60048

Convert Eloquent Relationship into array for Form::select()

I want to be able to generate a form select with 'optgroups' for my relationships.

This code works:

        foreach($old_project as $project)
        {
            foreach ($project->units as $unit)
            {
                $new_project[$project->name][] = $unit->name;
            }
        }

then in my view:

 {{ Form::select('units', $new_project) }}

But it doesnt seem right. I tried doing $old_project->toArray() - but that doesnt work either.

I looked at this forum post - so I also tried doing ->list() - but I couldnt seem to get it to work.

Is there a better way of doing this in Laravel 4?

edit:

This is my end goal - something like this:

<select id="optgroup3" name="unit">
   <optgroup label="Project1">
         <option value="1">Option 1</option>
         <option value="2">Option 2</option>
   </optgroup>
   <optgroup label="Project2">
         <option value="3">Option 3</option>
         <option value="4">Option 4</option>
   </optgroup>
</select>

p.s. I DONT want to do this if I can avoid it - I want to use Form::select() and keep it clean:

<select id="optgroup3" name="unit">
       @foreach($units as $project)
             <optgroup label="{{{ $project->name }}}">
                    @foreach($project->units as $unit)
                          <option value="{{{ $unit->id }}}">{{{ $unit->name }}}</option>
                    @endforeach
             </optgroup>
       @endforeach
</select>

Upvotes: 1

Views: 1264

Answers (1)

Dwight
Dwight

Reputation: 12450

I think the command you're after is in fact lists(). Try:

Project::lists('name', 'id')

Upvotes: 4

Related Questions