Search code examples
phplaravel-4dynamic-datahtml-select

how to preform a dynamic select dropdown in laravel 4


I've got my relationships setup where my projects are related to clients, what I want to do is to be able to select a select in my create project view via drop down list.

This can be achieved as so:

{{ Form::select('client', array('s' => 's', 'm' => 'm'), 's');}}

However I'm not sure how I would do this dynamically from the data I am retrieving from the database, the code I have so far is:

{{ Form::open(array('action' => 'ProjectController@store', 'id' => 'createproject')) }}
  <div class="form-group">
  <? $projects = Auth::user()->clients; ?>
@if (Auth::check())
    @if (count($projects) > 0)
   @foreach ($projects as $client)

{{ Form::select('client', array('client_one' => 'client_one', 'client_two' => 'client_two'), 'client_one');}}

   @endforeach 
   @else
    <h3>You have no projects click <a href="/project/create">here to create a project</a></h3>
@endif
@endif
</div>
<div class="form-group">
    {{ Form::label('project_name', 'Project Name') }}
    {{ Form::text('project_name', Input::old('project_name'), array('class' => 'form-control')) }}

</div>

Can anyone point me into the direction of how I can populate this select field dynamically?

Thanks in advance!


Solution

  • Doing the data processing in the view is not a good idea. What you should do is prepare the array in the controller and use that array in the view.

    In your controller.

        $clients = Auth::user()->clients;
    $client_selector = array();
    
    foreach($clients as $client) {
        $client_selector[$client->name] = $client->name; // I assume name attribute contains client name here
    }
    
    return View::make('your.view', array(.., 'client_selector' => $client_selector, ...));
    

    In your view.

    @if(count($client_selector)>0)
        {{Form::select('client', $client_selector, array_values($client_selector)[0])}}
    @endif