【问题标题】:Update Multiple Rows of Database using Laravel 8使用 Laravel 8 更新多行数据库
【发布时间】:2021-06-03 17:20:25
【问题描述】:

我想使用界面表单更新来更新数据库中的多个数据。下面的表格显示了从数据库中显示的数据,输入保存按钮后会更新。

下面是我的界面

以下是我的代码

html:

<form action="{{ route('people.update', $id) }}" method="post">
@csrf
{{ method_field('PATCH') }}
@foreach($peoples as $people)
  <tr>
   <td>
    <input type="checkbox" class="name" name="name" value=""/>&nbsp;&nbsp; {{$people->name}}
   </td>
   <td>
    <input type="number" class="age" value="{{$people->age}}" name="age" disabled />
   </td>
  </tr>
@endforeach
<button type="submit" name="button" class="btn btn-primary float-right" style="background-color: green;">Save</button>
</form>

Javascript/Jquery:

<script>
$(document).ready(function () {
        $('.name').on('change', function () {
            let input = $(this).closest('tr').find('input.age')
            input.prop("disabled", !$(this).is(':checked'));
            input.val('');
        });
      });
</script>

控制器

public function update(Request $request, $id)
    {
        //
        $people = People::find($id);
        $people->age=$request->input('age');
        $people->save();
        return redirect('people');
    }

问题:

我无法将表单更新到数据库,问题可能与控制器有关。

如何为这个场景设置控制器。

谢谢

【问题讨论】:

  • 您是否收到任何错误消息?尝试将dd($request-&gt;all()) 添加到控制器代码的开头以查看age 是否被正确传入(您可以对id 执行相同操作以确保其正确)。

标签: php html database laravel


【解决方案1】:

就在我的头顶上,在刀片中使用它:

    @foreach($people as $person)
       <tr>
          <td>
             <input type="checkbox" value="{{$person->id}}" name={{ "people[". $person->id ."][id]"}} />
          </td>
          <td>
              <input type="text" value="{{$person->name}}" name={{ "people[". $person->id ."][name]"}}  />
          </td>
          <td>
              <input type="number" value="{{$person->age}}" name={{ "people[". $person->id ."][age]"}}  />
           </td>
         </tr>
         <br>
  @endforeach

然后用这个内部控制器验证选定的那些,获取选定的 id:

foreach(request('people') as $id => $person) {
     if(array_key_exists($person->id, $person)){ //other validations here maybe
         People::findOrFail($id)->update(['age'=>$person->age]); //not ideal for large amounts, but you get the idea here.
     }
     
}

【讨论】:

  • 错误说 $id is undefined in
  • @wanprogrammer 那是因为你的路由定义,你使用 $id 作为更新路由参数,如果你用我的方式,重新定义你的更新后路由, $id 参数不是从还有更多。祝你好运。
【解决方案2】:

您的 $id 是针对特定人的,但您要更新的是所有选定的人,请尝试使用 jquery 将所有选定的 id 传递给控制器​​。

【讨论】:

  • 怎么做?你能告诉我吗?对不起,我是新手
  • 或者,将 $people->id 作为复选框的值传递,更简单
  • 谢谢你的想法,但传递 $people->id 作为复选框的值也产生了同样的错误。我认为控制器的整个代码是错误的
猜你喜欢
  • 2021-04-27
  • 2015-04-16
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
相关资源
最近更新 更多