Lovelock Lovelock - 1 year ago 98
PHP Question

Laravel 5 - Checking if a user has 'voted' when returning all votes for the resource as a relationship

I am making a voting system for a link sharing website I am working on.

When a user votes on a link as a new row is added to the db with the link id and user id.

When showing these links in my controller I call a relationship (votes):

$links = Link::orderBy('created_at', 'desc')->with('votes')->paginate(20);

And the relationship in the model

public function votes()
return $this->hasMany('\App\LinkVote');

In my view I am running a foreach on the $links to display each one. My aim is to show a different button if the user has already voted for that link.

When dd'ing $link->votes I get:

enter image description here

How can I check (in my view and in the foreach) if the currently logged in user is in that array of votes?

Answer Source

You can try contains():

$link->votes->contains('user_id', auth()->user()->id);

Or where() with count():

if ($link->votes->where('user_id', auth()->user()->id)->count()) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download