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

fabricecw's avatar

Intermediate table - Check if user already exists

Hi

I'm working on a voting system. I've these three tables/models.

  • User
  • Voting
  • UserVoting

The user can vote once on each voting.

If the user hasn't vote, it should create a new entry in the UserVoting with user-id, voting-id and the users vote.

If the user already voted on a voting, it should update the UserVoting entry.

I know there are many ways to do that. But what would be a very clean variant?

Regards,

0 likes
4 replies
jekinney's avatar

Depending on the relationship (many to many or has many)

if it's many to many you can use the sync method.

Warning: Sync will delete all occurrences and then add new ones. So if you depend on timestamps, not going to work.

The second method will just update...


auth()->user()->voting()->sync($vote_id, ['vote_info' => $vote_info]);


if(auth()->user()->voting()->contains($vote_id) {
    auth()->user()->voting()->updateExistingPivot($vote_id, ['vote_info' => $vote_info]);
} else {
    auth()->user()->voting()->attach($vote_id, ['vote_info' => $vote_info]);
}



https://laravel.com/docs/5.3/eloquent-relationships#updating-many-to-many-relationships

Please or to participate in this conversation.