Laravel 5 - 在将资源的所有投票作为关系返回时,检查用户是否已经“投票”
问题描述:
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);
if ($link->votes->where('user_id', auth()->user()->id)->count()) {