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:
How can I check (in my view and in the foreach) if the currently logged in user is in that array of votes?
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()) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With