从Laravel中的数据库中选择Multiple dropdwon list

时间:2019-02-01 10:30:46

标签: mysql html5 forms laravel-5

在我的Web应用程序中,我已使用多个选择选项从@IBAction func btnClick(_ sender: UIButton) { let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert) alert.addTextField { (textField) in DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { alert.textFields![1].becomeFirstResponder() }) } let okAction = UIAlertAction(title: "Ok", style: .default) alert.addAction(okAction) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true)} 向数据库添加了多个数据。

在我的数据库列中,如下所示。

json_encode

现在,我想检索这些数据以进行编辑和更新。我的看法就像附件图片

enter image description here

我的代码如下所示

["Agriculture & Food Processing","Automobiles","Banking & Financial Services"]

那么我该如何从数据库中选择上面的列表。

1 个答案:

答案 0 :(得分:0)

实际上,您不需要手动对其进行json_encode,laravel可以选择cast数组/ json的任何属性:

我们假设您的型号名称为Item

//Model
class Item{
   protected $casts = [
      'industry' => 'array'
   ]
//snap
}
//Controller
class ItemController extends Controller{
   //snap   
   public function update($id,\Request $request){
      $item = Item::findOrFail($item);
      // no need to json_encode! laravel handle this magically!
      $item->industry = $request->industry;
      $item->save();
   }
   //snap
   public function show($id){
      $item = Item::findOrFail($id);
      return view('item.show',compact('item'));
   }
}
@php
   // just making an array of industry options, so later we will iterate on it.
   $industries = [
      'Agriculture & Food Processing',
      'Automobiles',
      'Banking & Financial Services',
      //list all the industries here
   ];
@endphp
<select id="industry" name="industry[]" class="form-control" multiple>
   <!-- default value -->
    <option value="">Select Option </option>
    @foreach($industries as $industry)
       <!-- if industry found in current item's industry field we add selected to it -->
       <option @if(in_array($industry,$item->industry)) selected @endif>{{$industry}}</option>
    @endforeach
  </select>