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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?