duanpuqi9965 2016-11-09 23:20
浏览 40
已采纳

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:

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?

  • 写回答

1条回答 默认 最新

  • dtyw10299 2016-11-09 23:25
    关注

    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()) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序