doumei1955 2017-08-20 14:16
浏览 66
已采纳

Laravel如何从数据库中填充选择框

i have a database table that store list of country,now am trying to get the list of country in a dropdown form,but is not working, maybe am missing something.this is my controller code

` public function details($id){
        //fetch post data
        //$post = Post::find($id);

        $country_options = Country::pluck('country', 'id');
        $country_options = DB::table('regions')->orderBy('country', 'asc')->pluck('country','id');

        //pass posts data to view and load list view
        return view('dashboard')->with('country_options',$country_options);

    }`

and the code that echo the dropdown in my form look like this ` '

@foreach($countries as $country)'+
               '<option value="{{ $country->id }}"> {{ $country->country }}</option>'+
               '@endforeach'+`

and my route looks like this

Route::get('/Business', 'BusinessController@details')->name('Business');

but i keep getting this error message

Undefined variable: countries (View: C:\xampp\htdocs

have made research but could not fine the solution. any help would be appreciated with proper documentation/explanation.thanks

  • 写回答

3条回答 默认 最新

  • douma5954 2017-08-20 14:37
    关注

    Your mistake is that your passing one variable name to your view and trying to read with another name. I made some quick example for you. Here my table is "Pais" ("Country" in portuguese), and use an clorure route for the callback function. (Lavarel 5.4)

    Route (web.php):

    Route::get('/test', function () {
        $countries = \App\Pais::all();
        return view('test_stackoverflow')->with(['countries' => $countries]);
    });
    

    View (test_stachoverflow.blade.php):

    <select name="countries" id="countries">
      @foreach($countries as $country )
        <option value="{{ $country->id }}">{{ $country->name }}</option>
      @endforeach
    </select>
    

    Result


    Another option, if you want to stay with the pluck method:

    Route (web.php):

    Route::get('/test', function () {
      /* $countries = \App\Pais::pluck('name','id'); */
      // or
      $countries = DB::table('pais')->pluck('name','id');
      return view('test_stackoverflow')->with(['countries' => $countries]);
    });
    

    View (test_stachoverflow.blade.php):

      <select name="countries" id="countries">
        @foreach($countries as $id => $country )
          <option value="{{ $id }}">{{ $country }}</option>
        @endforeach
      </select>
    

    Both solutions have the same result in the generated HTML.

    Hope this can help you! Best regards.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?