Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 785
Lovelock Avatar asked Nov 09 '16 23:11

Lovelock


1 Answers

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()) {
like image 175
Alexey Mezenin Avatar answered Oct 24 '22 17:10

Alexey Mezenin