簡體   English   中英

Laravel 5將ID從數據庫傳遞到 <select>值

[英]Laravel 5 Pass the id from the DB to the <select> value

我是php框架的新手,並且正在使用Laravel創建CRUD應用程序。 問題是,當我嘗試將類別的ID從DB傳遞到View的值時,出現錯誤:

htmlentities()期望參數1為字符串,給定數組(視圖:C:\\ wamp \\ www \\ vecrud \\ resources \\ views \\ products \\ create.blade.php)

控制者

public function create()
{
    $products_create = categories::all()->lists('category');
    $categ_id = categories::all()->lists('id');

    return View::make('products.create', compact('products_create', 'categ_id'));
}   

視圖

{!! Form::label('category', 'Categorie') !!} <br />
{!! Form::select('category', $products_create, Input::old('category'), array('value' => $categ_id)) !!}

值( id )和選擇選項的文本( category )應該在同一數組中。 我想您正在尋找這個:

$category_list = categories::all()->lists('category', 'id');

return View::make('products.create', compact('category_list'));

視圖:

{!! Form::select('category', $category_list, Input::old('category')) !!}

另外,您不需要在lists()之前調用all() lists()

$category_list = Categories::lists('category', 'id');

使用lists()方法,第一個參數是數組值,第二個可選參數是用於數組鍵的屬性。 因此,如果要從數據庫中使用主鍵作為鍵的值,則可以執行以下操作:

$options = $model->lists('name', 'id');

然后,您可以將此數組直接傳遞給select表單幫助器:

Form::select('name', $options, null, ['class' => 'form-control']);

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM