Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Performing update queries given arrays of 'name' attributes

Hello,

In the frontend I have a form wrapping a table with the name attributes being arrays (with the ids from the DB being the keys):

<form>
  <table>
    @foreach($rows as $row)
    <tr>
      <td><input type="email" name="email[{{$row->id}}]"></td>
      <td><input type="text" name="username[{{$row->id}}]"></td>
    </tr>
    @endforeach
  </table> 
</form>

When the form data is sent to the backend, it is grouped by the name attributes:

[
  "email" => [11 => "[email protected]", 332 => "[email protected]"],
  "username" => [11 => "foo", 332 => "bar", 404 => "baz"],  
]

I need to update the DB where the id in the DB equals the id from the input. What I do is to first "regroup" the input by the id via PHP, so the end result is:

$data_to_update = [
  11 => ["email" => "[email protected]", "username" => "foo"],
  332 => ["email" => "[email protected]", "username" => "bar"],
  404 => ["username" => "baz"],
]

Then I can iterate each and update:

foreach ($data_to_update as $id => $data) {
    DB::table('users')
      ->where('id', $id)
      ->update($data);
}

But is there a way to skip the PHP regrouping part and do it on the original structure (Without extra queries)?

Thanks

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

rename your form entries for easier management later

  <td><input type="email" name="rows[{{ $row->id }}][email]"></td>
  <td><input type="text"  name="rows[{{ $row->id }}][username]"></td>
1 like
Ligonsker's avatar

@Snapey you are a genius, thank you!

Btw, is this something that you've used before? Is it ok to do? I just wonder if I did something wrong in the first place that made it sort of "complicated"? Or it's still alright

Please or to participate in this conversation.