How to update/sync table data for each row from input field array ?

Posted 2 months ago by lonerunner

So i have multiple input field into array

<input type="text" name="messages[{{ $i }}]" id="messages" class="form-control" >

Each $i represents loop array, and from that array i need to save each one on separate row, at the same time that need to be kinda synced so deleting old data for that user and inserting new one.

Currently i have this, and this actually works, problem is, it saves row's in database in kinda odd way that they don't go arranged in order.

So in my User model i have this

public function messages() {
      return $this->hasMany(Message::class);

When i hit update button on my page, in my UserController i have this:

$user = User::find($id);

$user->name = $request->name;
$user->lastname = $request->lastname;



if(is_array($request->messages)) {
  foreach($request->messages as $message) {
         $user->messages()->create(['user_id' => $user->id, 'message' => $message]);

So this works, but order of messages in table is out of order:

| id | user_id |         message          |
|  6 |      12 | This is third message    |
|  5 |      12 | And now second message   |
|  4 |      12 | First message            |
|  7 |      12 | This should be forth one |

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.