检查帖子是否被用户喜欢.拉拉维尔


Check if post is liked by user. Laravel

当我

显示用户的所有帖子时,我想检查经过身份验证的用户是否喜欢帖子。这是我现在的做法:

public function index(){
    $posts = Post::orderBy('created_at', 'desc')->get();
    $user = Auth::user();
    $liked = Post::with('user')
        ->whereHas('like', function ($query) use ($user) {
            $query->where('user_id', '=', $user->id);
        })->get();
    return view('index', compact('posts', 'liked'));
}

当我在 HTML 中执行此操作时:

@if($liked)
    <button class="[ btn btn-primary ]">
    <i class="fa fa-thumbs-o-up" aria-hidden="true"></i> You like this</button>
@else
    <a href="/patinka/{{$p->id}}" type="button" class="[ btn btn-default ]">
    <i class="fa fa-thumbs-o-up" aria-hidden="true"></i> Like</a>
@endif

总是得到"你喜欢这个",即使我不喜欢那个帖子。有人可以告诉我这段代码有什么问题吗?

首先,让我们确保你的关系设置正确。

帖子模型:

public function like() 
{ 
    return $this->HasMany('App'Like'); 
}

喜欢模型

public function user() 
{ 
    return $this->hasOne('App'User', 'id', 'user_id'); 
}

然后将两个Post调用组合在一起并像这样运行它:

$user_id = Auth::id();
$posts = Post::with(['like' => function ($like) use ($user_id) {
    return $like->whereHas('user', function ($user) use ($user_id) {
        $user->where('id', $user_id);
    })->get();
}])->get();
return view('index', compact('posts'));

然后,在您的视图中,您可以进行检查:

@foreach ($posts as $post)
    @if(count($post->like))
        ...
@endforeach