0

I have 2 models, one is a Poll, and another is an User. I have set up a M:N relationship between both of them:

User.php

public function votedPolls() {
    return $this->belongsToMany('Polls', 'votes');
}

Poll.php

public function voters() {
    return $this->belongsToMany('User', 'votes');
}

And it all works nicely. When I vote on a poll, the table votes get populated properly. But now I want to check inside the controller if a user has already voted in a poll.

I figured it would be something like this, but I am not sure of the syntax. I tried this (which does not work):

$voters = $poll->voters()->where('id', '=', $user->id)->first();
$voted = count($voters) == 1;

How could I achieve this?

Enrique Moreno Tent
  • 24,127
  • 34
  • 104
  • 189

1 Answers1

1

count is preferred way of checking if relations exist.

Your code didn't work because your pivot table also has id column and where clause was ambiguous, so change it to:

where('users.id','=',$user->id)
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157