2017-08-20 55 views
1

我有一個數據庫表,存儲國家的名單,現在我試圖以下拉形式獲得國家的名單,但沒有工作,也許是缺少something.this是我的控制器代碼Laravel如何從數據庫填充選擇框

` 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); 

    }` 

和呼應下拉我的形式看起來像這樣''

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

和我的路線是這樣的

Route::get('/Business', '[email protected]')->name('Business'); 
0123碼

但我不斷收到此錯誤信息

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

已經取得的研究,但不能罰款的解決方案。 任何幫助將不勝感激與正確的文件/ explain.thanks

+0

我注意到的第一件事是你使用'$ countries'在視圖中,但在控制器中,您正在傳遞'country_options'來查看。 – Bostjan

回答

2

你的錯誤是,你傳遞一個變量名稱到您的視圖,並試圖用另一個名稱閱讀。我爲你做了一個快速的例子。在這裏,我的表格是「Pais」(葡萄牙語中的「Country」),並使用回調函數的clorure路線。 (Lavarel 5.4)

路線(web.php):

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

視圖(test_stachoverflow.blade.php):

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

Result


另一種選擇,如果你想留在採摘方法:

路線(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]); 
}); 

視圖(test_stachoverflow.blade.php):

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

兩種解決方案有生成的HTML中的結果相同。

希望這能幫助你! 此致敬禮。

+0

我認爲你的採摘不會工作....你已經嘗試過了,還是隻寫了代碼?因爲pluck現在返回一個集合而不是一個數組! – lewis4u

+0

你是對的,不是一個數組,是一個集合。但是這個工作,我在執行和測試之前粘貼在這裏。 說明:Collection類實現IteratorAggregate接口,該接口具有方法getIterator,在foreach語句中隱式調用。 鏈接: 收藏:https://laravel.com/api/5.4/Illuminate/Support/Collection.html IteratorAggregate:http://php.net/IteratorAggregate – renanpallin

1

你是從你的控制器不countries

通過country_options試試這個

@foreach($country_options as $country) 
    <option value="{{ $country->id }}"> 
     {{ $country->country }} 
    </option> 
@endforeach 
0

首先你不需要的$ id如果你想蓋爾所有類別與

relace控制器代碼:

public function details(){ 
    $country_options = Country::All(); 
    return view('dashboard',compact('countries')); 
} 
相關問題