简体   繁体   English

批量更新,在 laravel 中更新多行

[英]Bulk updating, update multiple rows in laravel

Am trying to update multiple data in laravel but the solutions am getting when i search on goole are not what am lookin for.我正在尝试更新 laravel 中的多个数据,但是当我在 goole 上搜索时得到的解决方案并不是我要寻找的。 here is mycode:这是我的代码:

In blade在刀片

<form action="{{url('users/update')}}" method='post'>
@foreach($data as $users)
 <tr>
<td>
  <input type="" name="id[]" value="{{ $users->id  }}">
  <input type="" name="names[]" value="{{ $users->name }}">
</td>
</tr>
@endforeach
<button type="submit">Submit</button> 
</form>

In Controller在控制器中

 public function updateuser(Request $request){
     
     $users = user::where("id" ,$request->$id)->update(["name" => $request->names]);
     
     return back()->with('success','Successfully');
   }

I want to be able to update lets say i have 10 records in the database i want to update all 10 using their respective IDs我希望能够更新假设我在数据库中有 10 条记录我想使用它们各自的 ID 更新所有 10 条记录

Thank you in advance先感谢您

If you really want to do it that way, you need to name your input something specific如果你真的想那样做,你需要为你的输入命名一些特定的东西

<form action="{{url('users/update')}}" method='post'>
    @foreach($data as $users)
        <tr><td>
            <input type="" name="names[{{ $users->id  }}]['name']" value="{{ $users->name }}">
        </td></tr>
    @endforeach
    <button type="submit">Submit</button> 
</form>

And your controller need to be你的控制器需要

public function updateuser(Request $request)
{
    $users = user::update($request->names);
    return back()->with('success','Successfully');
}

First if you want to update or do something you need to provide @csrf in the form.首先,如果您想更新或执行某些操作,您需要在表单中提供@csrf If you are doing update or delete method you need to provide @method('PUT') or @method('DELETE') .如果您正在执行更新或删除方法,则需要提供@method('PUT')@method('DELETE')

Second thing I am not sure that you can provide user:: , try User:: .第二件事我不确定您是否可以提供user:: ,请尝试User::

Here is what you asked for这是你要的

foreach($request->id as $key => $id) {
    User::where('id', $id)->first()->update([
        'name' => $request->names[$key]
    ]);
}

This should work fine:)这应该可以正常工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM