将选择的Laravel下拉选项传递到控制器中

时间:2014-04-27 19:53:44

标签: php laravel laravel-4

查看:

{{ Form::open(array('url'=>'agents/searchStaff', 
                    'class'=>'form-search', 
                    'role'=>'form')) }}

        <select class="form-control">
          @foreach ($company->users as $user)
          <option id="{{ $user->id }}" name="agent">
                      {{ $user->firstname }} {{ $user->surname }}
          </option>
          @endforeach
        </select>
{{ Form::close() }}

路线:

Route::post('agents/searchStaff', 'AgentsController@postSearchStaff');

控制器:

public function postSearchStaff()
{
    $agent_id = Input::get('agent');
    dd($agent_id); // For testing purposes - Always returns NULL.
}

我不确定为什么没有将选项值的ID传递给控制器​​。任何帮助和指导将不胜感激。

2 个答案:

答案 0 :(得分:0)

更改

 <select class="form-control">
     @foreach ($company->users as $user)
         <option id="{{ $user->id }}" name="agent">
             {{ $user->firstname }} {{ $user->surname }}
         </option>
     @endforeach
 </select>

 <select class="form-control" name="agent">
     @foreach ($company->users as $user)
         <option value="{{ $user->id }}">
             {{ $user->firstname }} {{ $user->surname }}
         </option>
     @endforeach
 </select>

答案 1 :(得分:0)

您需要将id={{ $user->id }}更改为value={{ $user->id }}

但是这个:

<select class="form-control">
  @foreach ($company->users as $user)
    <option id="{{ $user->id }}" name="agent">
      {{ $user->firstname }} {{ $user->surname }}
    </option>
  @endforeach
</select>

可以在你的模型中用一点糖完成一行:

// view
{{ Form::select('agent', $users, $selectedAgentId, $attributes) }}

// User model
public function getFullnameAttribute()
{
    return $this->attributes['firstname'].' '.$this->attributes['surname'];
}

// controller:
$users = $company->users->lists('fullname','id'); // Collection method