我需要检查用户是否喜欢这个帖子,不要再喜欢它了。问题是,当我的代码中有一个用户喜欢这个帖子时,我不喜欢和其他用户一样。我不知道为什么。
控制器:
$posts = Post::orderBy('created_at', 'desc')->paginate(10);
foreach($posts as $p){
foreach ($p->like as $like){
$like = Like::where('user_id', '=', Auth::user()->id)->get();
}
}
post.php中:
public function user(){
return $this->belongsTo('App\User');
}
public function like()
{
return $this->hasMany('App\Like');
}
Like.php:
public function user()
{
return $this->belongsTo('App\User');
}
public function post()
{
return $this->belongsTo('App\Post');
}
user.php的:
public function post(){
return $this->hasMany('App\Post');
}
public function like(){
return $this->hasMany('App\Like');
}
HTML
@if($like)
<i class="fa fa-thumbs-o-up liked pull-right" aria-hidden="true"></i>
@else
<a href="/like/{{$p->id}}">
<i class="fa fa-thumbs-o-up likeBtn pull-right" aria-hidden="true"></i></a>
@endif
答案 0 :(得分:1)
不要在控制器中执行循环。在视图中做(刀片)
已编辑的控制器
$posts = Post::orderBy('created_at', 'desc')->paginate(10);
$likes = Like::select('post_id')->where('user_id',Auth::user()->id)->get();
$likeArr=array_flatten($likes->toArray()); //convert multidimensional array to single array for easy access
return view('yourview',['posts'=>$posts,'likes'=>$likeArr]);
查看强>
@foreach($posts as $p)
@if(in_array($p->id,$likes))
<i class="fa fa-thumbs-o-up liked pull-right" aria-hidden="true"></i>
@else
<a href="/like/{{$p->id}}">
<i class="fa fa-thumbs-o-up likeBtn pull-right" aria-hidden="true"></i>
</a>
@endif
@endforeach
答案 1 :(得分:1)
如果您想检查Auth用户是否喜欢发帖,我就是这样做的。
Post.php
class Post extends Model{
public function likes(){
return $this->hasMany(Like::class);
}
public function isAuthUserLikedPost(){
$like = $this->likes()->where('user_id', Auth::user()->id)->get();
if ($like->isEmpty()){
return false;
}
return true;
}
}
Comment.php
class Comment extends Model{
public function post(){
return $this->belongsTo(Post::class);
}
}
在您看来,您可以用作:
{{ $post->isAuthUserLikedPost() ? 'do-something' : 'do-something else' }}