【问题标题】:Laravel handling array of inputsLaravel 处理输入数组
【发布时间】:2020-07-10 10:40:26
【问题描述】:

我有以下数据库:

id | name | age |
-----------------
 1 | John |  20 |
 2 | Jack |  29 |

我想在一个表单中编辑它们,并能够“添加更多”,然后根据需要保存/更新。 Laravel 如何做到这一点?

我目前的表格是这样的:

@foreach($people as $person)
    <input type="text" name="name[]" class="form-control" value="{{ $person->name }}">
    <input type="text" name="age[]" class="form-control" value="{{ $person->age }}">
@endforeach

然后在 Laravel 我收到$request-&gt;all() 如下:

  "name" => array:2 [▼
    0 => "John"
    1 => "Jack"
  ]
  "name" => array:2 [▼
    0 => "20"
    1 => "29"
  ]

我猜这是意料之中的,但与 Eloquent 一起工作并不方便。 这样做的 Eloquent/Laravel 方式是什么?

注意:在我正在开发的真实示例中,Name 是独一无二的。

使用 Laravel 7。

【问题讨论】:

    标签: laravel eloquent laravel-7


    【解决方案1】:

    您应该使用用户 ID 来识别每一行结果

    @foreach($people as $person)
        <input type="text" name="users[$person->id][name]" class="form-control" value="{{ $person->name }}">
        <input type="text" name="users[$person->id][age]" class="form-control" value="{{ $person->age }}">
    @endforeach
    

    你会得到如下请求:

    [
        "users" => [
            1 => [
                'name' => 'John',
                'age' => 20
            ],
            2 => [
                'name' => 'Jack',
                'age' => 29
            ]
        ]
    ]
    

    【讨论】:

    • 只是为了补充 Lloople 所说的,为控制器中的唯一名称添加规则。
    • 为什么名称应该是唯一的?我办公室有三个人叫John
    猜你喜欢
    • 2021-12-06
    • 2021-12-27
    • 2014-08-20
    • 2012-12-26
    • 2018-05-07
    • 1970-01-01
    • 2021-07-25
    • 2013-09-10
    • 1970-01-01
    相关资源
    最近更新 更多