Multi-select 下拉列表仅将最后一个 selected 值保存到数据库 - Laravel

Multi-select dropdown saves only the last selected value to the database - Laravel

我想将多 select 下拉列表 selected 名称以逗号分隔保存到数据库中。使用我的代码,它仅将最后一个 selected 值保存到数据库中。

Blade.php

<div class="form-group">
  <select name="team[]" id="team" class="selectpicker" multiple>
    @foreach ($tdropdown as $tdrop =>$id) 
      <option value="{{$id}}">{{$tdrop}}</option>   
    @endforeach
  </select>
</div>

控制器

public function empstore(Request $request){

   $employee = new employee();
   $employee->team = $request->team;

  $tarray = $request->input('team');
      
foreach ($tarray as $key => $n) {
   $employee->team = $tarray[$key];
   $result = DB::table('teams')->where('id', '=', "$employee->team")->value('name');
    // $employee->team = implode(',', $tarray);
   $employee->team = $result;
    //var_dump($result);
   $employee->save();
}
   //die();
 return redirect()->route('employee.index')->with('success','Data Added');
    
}

当我 var_dump($result); 它输出所有 selected 值如下。

string(2) "Team one" string(2) "Team two"

但是上面的代码只保存了最后一个selected值,这意味着只有“二队”到数据库。请帮助我将所有 selected 值保存到数据库。谢谢。

$teams = $request->input('team', []);

$employee->team = DB::table('teams')
    ->whereIn('id', $teams) // only find the ids we received
    ->pluck('name') // only get the 'name' column
    ->implode(','); // implode into a comma separated list

$employee->save();