Laravel自动选择选项

时间:2016-05-17 04:07:24

标签: php laravel laravel-5 laravel-5.1 laravel-5.2

我想让我的编辑是自动选择选项,但当我尝试是不工作。如果我点击id_cms_companies" 1"从我的表位置是自动选择并在第一个选择选项中显示。 它显示了表cms_companies的名称 在这里我的代码:

<select class='form-control' name='id_cms_companies'>
                        <option>- Companies -</option>
                        <?php 
                        $category = DB::table("cms_companies")->get();
                        foreach($category as $cat) 
                        {
                         if($cat->name == $row->id_cms_companies)
                         {
                          echo "<option value='$cat->name' selected>$cat->name</option>";
                         }
                         else
                         {
                          echo "<option value='$cat->name'>$cat->name</option>";
                         }
                        }
                         ?>
                        </select>

在这里我的控制器:

public function getEdit($id)  {
        $data['row'] = locations::find($id);
        return view('locations_form',$data);
    }

    public function postEditSave($id) {
        $simpan= array();
        $simpan['name']=Request::input('name');
        $simpan['id_cms_companies']=Request::input('id_cms_companies');

        DB::table('locations')->where('id', $id)->update($simpan);
        Session::flash('edit', 'Data berhasil di Edit');
        return Redirect::to('locations');
    }

这是我的表:

table locations

和我的

table cms_companies

2 个答案:

答案 0 :(得分:0)

您应该比较两个ID,没有ID与名称

if($cat->name == $row->id_cms_companies) //wrong
if($cat->id == $row->id_cms_companies) //correct

答案 1 :(得分:0)

您可以使用laravel html,它会自动执行

所以你可以这样做:

$category = DB::table("cms_companies")->get()->pluck('name', 'id');
echo Form::select('id_cms_companies', $category, $row->id_cms_companies, ['class' => 'form-control']);

在此处详细了解docs