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