Jeremy Belolo
Jeremy Belolo

Reputation: 4539

Laravel - updating a field on a relational table

I have a users table, an emails table and a user_email table. In that join table I have the user_id, email_id and is_confirm(boolean). When a user confirms his email, I want to update that field, and have tried to do so using the following methods:

In the User model :

public function emails() {
    return $this->belongsToMany('App\Email', 'user_email')->withPivot('is_confirm');
}

In the Email model :

public function users() {
    return $this->belongsToMany('App\User', 'user_email')->select(['user_email.is_confirm', 'user_email.id']);
}

I have tried:

$emailID = Email::where('email', $email)->first();
$pivot = Email::find($emailID->id)->users->first();
$pivot->is_confirm = 1;
$pivot->save();

and I have also tried:

$emailID = Email::where('email', $email)->first();
$emailID->users()->updateExistingPivot( $emailID->user_id, ['is_confirm' => 1] );

However, neither option works.

Do both of my model's relations look right? How can I go about updating this field?

Upvotes: 0

Views: 83

Answers (1)

Alex Harris
Alex Harris

Reputation: 6392

I think the answer is as follows:

User::find(1)->emails()->updateExistingPivot($emailId, ['is_confirm' => 1]);

But I am curious if there is any reason this is_confirm cannot be on the email table? Additionally, as mentioned below, if an email can only by tied to one user, consider moving the foreign key user_id directly on to the email table along with the is_confirm.

Upvotes: 1

Related Questions