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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化