php - Laravel 将数组放入选择框

标签 php laravel laravel-3

我的选择框出现了一些问题,我会将所有可用的类别放入

在我的 Controller 中,我正在使用这个片段:

 return View::make("stories.add")
        ->with("title","Indsend novelle")
        ->with("categories", Category::all());

在我看来,我正在尝试将所有类别放入选择框中:

 {{Form::select("category", $categories)}}

我可以做这个,但是那行不通,因为 Form::select 必须是一个数组?

@foreach ( $categories as $category )
    {{$category->name}}
@endforeach

怎么办?

我已经做了这个并且它可以工作,但是它看起来太丑了而且对用户不友好,有什么建议吗?

  $test = Category::all(); $myArray = array();
    foreach ( $test as $o):
          $myArray[] = $o->name;
    endforeach;

    return View::make("stories.add")
        ->with("title","Indsend novelle")
        ->with("categories", $myArray);

变量转储:

    array(2) {
      [0]=>
      object(Category)#36 (5) {
        ["attributes"]=>
array(4) {
  ["id"]=>
  string(1) "1"
  ["name"]=>
  string(12) "Alderforskel"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["original"]=>
array(4) {
  ["id"]=>
  string(1) "1"
  ["name"]=>
  string(12) "Alderforskel"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["relationships"]=>
array(0) {
}
["exists"]=>
bool(true)
["includes"]=>
array(0) {
}
}
       [1]=>
   object(Category)#39 (5) {
  ["attributes"]=>
  array(4) {
  ["id"]=>
  string(1) "2"
  ["name"]=>
  string(7) "Bondage"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["original"]=>
 array(4) {
  ["id"]=>
  string(1) "2"
  ["name"]=>
  string(7) "Bondage"
  ["created_at"]=>
  string(19) "0000-00-00 00:00:00"
  ["updated_at"]=>
  string(19) "0000-00-00 00:00:00"
}
["relationships"]=>
array(0) {
}
["exists"]=>
bool(true)
["includes"]=>
array(0) {
}
}
}

最佳答案

这样使用:

$categories = Category::pluck('name', 'id');

return View::make('....', compact('categories'));

现在在 View 中:

{{ Form::select('selectName', $categories, null); }}

编辑:在文档中找到 Query builder # Select看看这个

关于php - Laravel 将数组放入选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17162876/

相关文章:

php - 将数组转换为 XML 或 JSON

javascript - 如何使用 xmlhttprequest 将值作为变量传输?

laravel - where 语句内有多个 where

php - Laravel - session 不与数据库驱动程序保持一致

php - 如何获取待上传记录的ID(自增)?

PHP 脚本越来越慢(文件阅读器)

php - 避免因页面刷新而提交的最佳方法

laravel - 如何传递与 vue 模板相关的 Eloquent 数据

php - 在 PHP 中处理动态数量的表单字段的最佳方法?

php - 在 Laravel 中检查 session 超时