Home > Back-end >  multiple update in laravel from input form with name as id and name as names
multiple update in laravel from input form with name as id and name as names

Time:12-26

Am try to update the data in my table from input form using eloquent: This the output of my code

enter image description here

So what i want is that when i click submit i want all the data to be update respective of its ID

My table looks like this

enter image description here

Here is my code in Blade

<form action="{{url('update/users')}}" method="post">
 @csrf
<table>
  <tbody>
     <tr>
         <th>ID</th>
         <th>Names</th>
     </tr>
     @foreach($data as $users)
     <tr>
     <td><input type="" name="id" value="{{$users->id}}" ></td>
     <td><input type="" name="name" value="{{$users->name}}" ></td>
     </tr> 
     @endforeach  
  </tbody>  
</table>
<button type="submit">Submit</button>
</form>

in Controller

  public function update(Request $request){
     
     //code here
     // $users = Users::

     return back()->with('success','Successfully');
   }

CodePudding user response:

to update multiple resources in db you can accomplish this using:

first you must edit your form to send multiple data to server : you must set type of inputs. the type of id input must be hidden becasue user can not edit it . this input will be used in controller to determine the user to update .

you can send a array parameter to server. to accomplish this you can set the name attribute of input as array

<form action="{{url('update/users')}}" method="post">
 @csrf
<table>
  <tbody>
     <tr>
         <th>ID</th>
         <th>Names</th>
     </tr>
     @foreach($data as $key=> $users)
     <tr>
     <td><input type="hidden" name="users[{{$key}}][id]" value="{{$users->id}}" ></td>
     <td><input type="text" name="users[{{$key}}][name]" value="{{$users->name}}" ></td>
     </tr> 
     @endforeach  
  </tbody>  
</table>
<button type="submit">Submit</button>
</form>

so the users in request is a array that each element is array with id and name key

public function update(Request $request){
    
       foreach($request->input('users') as $user){
         $id=$user['id'] ;
         $name=$user['name'] ;
         User::find($id)->update([
            'name'=>$name 
           ]) ;
      }
   

     return back()->with('success','Successfully');
   }
  • Related