【问题标题】:Trying to populate a form select with user information尝试使用用户信息填充表单选择
【发布时间】:2017-02-04 10:55:31
【问题描述】:

我正在尝试使用 larval 使用数据库中的用户信息填充表单选择。我也在使用 laravelcollective.com 的表单助手。

这是控制器中的代码

public function create()
{

    $users = DB::table('users')->select('id', 'firstname as name')->get();

    return view('messages.create')->with('users');
}

即使我在这里使用 querybuilder,它也可以工作。它返回 id 和 firstname 字段作为名称。所以我认为这不是问题。

这是 create.blade.php 文件中的代码

{{ Form::select('user', [$users], null) }}

使用此代码,我得到一个工作页面,选择框中没有任何内容。

使用此代码

{!! Form::select('user_id', $users, null) !!}

我得到一个为 foreach() 错误提供的无效参数

还有这段代码

{!! Form::select('user_id', [$users], null) !!}

我得到一个工作页面,选择框中没有任何内容。

所以我尝试了任何不同的东西,但没有任何效果。

【问题讨论】:

    标签: forms laravel laravel-form


    【解决方案1】:

    你需要传递一个数组作为第二个参数:

    {!! Form::select('user_id', $users, null) !!}
    

    您可以使用pluck() 方法,这是为Form::select 构建数组的非常方便的方法

    $users = User::pluck('firstname', 'id');
    

    或者你可以这样做:

    $users = DB::table('users')->pluck('firstname', 'id');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多