0
votes

I'm trying to understand some advanced eloquent commands and on the Laravel official documentation, I can't find any mention of the updateExistingPivot method.

I just found a little documentation here:
https://laravel.com/api/8.x/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.html#method_updateExistingPivot

Can somebody help me to understand it with also a simple example?

1

1 Answers

0
votes

After a bit of further research, I found an answer to my question.

The purpose of the Eloquent updateExistingPivot() method is too updating an extra attribute on a pivot table of a Many to Many relationship.

This method accepts the pivot record foreign key and an array of attributes to update.

For instance, if we have a User-Message many to many relationship where:

  • a message can be sent to many users.
  • a user can receive many messages.

/app/User.php

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

/app/Message.php

public function users()
{
    return $this->hasMany(User::class);
}

And we want to record the status of each message if it has been delivered to the user.

So we define a status attribute in the pivot table.

The pivot table user_message:

  • id
  • user_id
  • message_id
  • status

When the message is shipped to a specific user, I can set the status to 'sent' in this way:

$user = User::find(1);
$messageId = 2;
$user->messages()->updateExistingPivot($messageId, ['status' => 'sent']);

This will update the pivot table row with user_id=1 and message_id=2 setting the status attribute to 'sent'.