Skip to content

Commit

Permalink
perf: rewriting $isLiked in ChallengeResource
Browse files Browse the repository at this point in the history
  • Loading branch information
muhammadmp97 committed Sep 6, 2023
1 parent 4ad712e commit 9e31949
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
4 changes: 1 addition & 3 deletions app/Http/Resources/ChallengeResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ class ChallengeResource extends JsonResource
{
public function toArray(Request $request): array
{
$isLiked = $this->likes->contains(fn ($like) => $like->user->id === $request->user()->id);

return [
'id' => $this->id,
'user' => TinyUserResource::make($this->user),
'status' => $this->status,
'text' => $this->text,
'continued_at' => $this->continued_at,
'is_liked' => $isLiked,
'is_liked' => $this->isLikedBy($request->user()->id),
'like_count' => $this->likes_count,
'comment_count' => $this->comments_count,
'created_at' => $this->created_at,
Expand Down
8 changes: 8 additions & 0 deletions app/Models/Challenge.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ public function scopeByUserId(Builder $query, $userId = null): void
}
}

public function isLikedBy($userId): bool
{
return $this
->likes()
->where('user_id', $userId)
->exists();
}

public function user()
{
return $this->belongsTo(User::class);
Expand Down

0 comments on commit 9e31949

Please sign in to comment.