在laravel

时间:2018-12-05 09:57:34

标签: php laravel laravel-5 implode

我正在使用laravel 5.5 我有一个多选下拉菜单。如果我不选择任何值,则会产生错误。 “ implode():传递了无效的参数”

<select  multiple="multiple" name="language[]">
@foreach($language_data as $language)
   <option value="{{$language->language_id}}">{{$language->language_name}}</option>
@endforeach
</select>

控制器

  $language = $request->input('language');
  $language = implode(',', $language);
 DB::table('language')->insert(['language' => $language,]);

4 个答案:

答案 0 :(得分:0)

仅在以下情况下使用简单的

if($request->input('language') !== ''){
  $language = $request->input('language');
  $language = implode(',', $language);
 DB::table('language')->insert(['language' => $language,]);
}

如果需要在后端定义一种语言(如以下未选择任何一种语言),则可以回退

$request->input('language') !== '' ? $language = $request->input('language') : $language = 'en_GB';

$language = implode(',', $language);
DB::table('language')->insert(['language' => $language,]);

答案 1 :(得分:0)

尝试一下,应该解决问题

$language = ''; //set default language here
if($request->input('language')) {
   $language = $request->input('language');
   $language = implode(',', $language);
}
DB::table('language')->insert(['language' => $language,]);

答案 2 :(得分:0)

在爆裂之前只需进行检查即可。

  $language = $request->input('language');
  if (!empty($language)) {
     $language = implode(',', $language);
  } else {
     $language = '';
  }
  DB::table('language')->insert(['language' => $language]);

答案 3 :(得分:0)

$language = optional(collect($request->input('language')))->implode(',');

DB::table('language')->insert(['language' => $language]);

从$ request值中获取一个集合,如果'language'不是必需属性,则包装为可选,并强制结果。