My Model has the following one-to-many
relationship
class Comment extends Model
{
public function likes(): HasMany
{
return $this->hasMany(CommentLike::class);
}
}
In my Controller
I want to get all Comments
alongside with a boolean value which indicates if the current user exists in the likes
table
$result = Comment::with(['user', 'likes' => function($q) use($user){
$q->where('user_id', $user->id);
}])
->withCount('likes')
->where('post_id', $postId)
->get();
Currently the above query will return the correct result alongside with a row from the likes table if the user is found.
I'm looking for a proper way to return a boolean value to indicate if the user has liked the comment instead.
CodePudding user response:
First, you can find how many likes does user make to the comment, in this way.
$likes = Comment::whereHas(['likes' => function($q) use ($user){
$q->where('user_id', $user->id);
})->where('post_id', $postId)->count();
Then using $likes
variable value, you can conditionally create a boolean value and assign to new variable or same $likes
variable.
$hasLike = $likes ? true : false;
CodePudding user response:
You can make use of withExists()
method. It's not one of the best documented ones, but I think it's quite simple.
In your example:
$result = Comment::with(['user', 'likes' => function($q) use($user){
$q->where('user_id', $user->id);
}])
->withCount('likes')
->where('post_id', $postId)
->get();
Consider changing it to:
$result = Comment::with(['user', 'likes'])
->withCount('likes')
->withExists(['likes' => function ($query) use ($user) {
$query->where('user_id', $user->id);
}])
->where('post_id', $postId)
->get();
Result model will contain additional bool property likes_exists
where true
means that $user
liked the comment and false
means that they didn't do it.