简体   繁体   中英

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. 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

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. If you are doing update or delete method you need to provide @method('PUT') or @method('DELETE') .

Second thing I am not sure that you can provide user:: , try 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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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