zoukankan      html  css  js  c++  java
  • laravel 记录一次赞 与 取消赞 的功能开发

    <p>
      @if(!$post->agree(Auth::id())->exists())
        <a href="{{route('user.post.agree',['id'=>$post->id])}}" class="btn btn-info">赞</a>
      @else
        <a href="{{route('user.post.unAgree',['id'=>$post->id])}}" class="btn btn-default">取消赞</a>
      @endif
    </p>

    如上所示,赞和取消赞是两个链接,对应到控制器里的两个方法去实现赞和取消赞

    //赞文章
    public function agree($id)
    {
    Agree::firstOrCreate(['post_id'=>$id,'user_id'=>Auth::id()]);
    return redirect()->back();
    }

    //取消赞文章
    public function unAgree($id)
    {
    Agree::where([['post_id',$id],['user_id',Auth::id()]])->delete();
    return redirect()->back();
    }

    在赞的表主要有两个字段 user_id 和 post_id 哪个用户对哪个文章进行了赞,赞和取消赞既是对这个表进行添加记录和删除记录

    不论是在控制器还是视图 都可以直接使用 Auth::id() 来进行获取登陆用id ,当然,你得在上面 use 下Auth门脸类

    //一篇文章-当前登陆用户的赞
    public function agree($user_id)
    {
    return $this->hasOne('AppAgree')->where('user_id',$user_id);
    }

    //一篇文章对应多个赞
    public function agrees()
    {
    return $this->hasMany('AppAgree');
    }

    在post模型中,对赞表进行关联,有两个关联,一个是当前登陆用户的对当前赞获取,一个是当前文章的所有赞的获取

    在视图中进行判断显示赞还是取消赞,使用模型关联的agree来判断

    如最上面的代码所示使用当前文章$post->agree( Auth::id() )->exists();   当前文章$post的关联模型agree的agree方法,传入参数为当前用户id,返回值为,赞表中user_id为当前登陆用户的id , post_id为当前显示的文章的id的记录,exists方法来判断是否存在,如果存在这条记录,就显示取消赞,如果不存在,就显示赞

  • 相关阅读:
    LeetCode Single Number
    Leetcode Populating Next Right Pointers in Each Node
    LeetCode Permutations
    Leetcode Sum Root to Leaf Numbers
    LeetCode Candy
    LeetCode Sort List
    LeetCode Remove Duplicates from Sorted List II
    LeetCode Remove Duplicates from Sorted List
    spring MVC HandlerInterceptorAdapter
    yum
  • 原文地址:https://www.cnblogs.com/muwu/p/9019492.html
Copyright © 2011-2022 走看看