Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25267

Laravel 4 - Finding out if an M:N relation exists between 2 models

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?

Upvotes: 0

Views: 154

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

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)

Upvotes: 1

Related Questions