Answer the question
In order to leave comments, you need to log in
Print value of Laravel model?
there is a Comment model
in it, I make a function to display the like value for the user. If he is a linkul then 1, if he is a dislike then 0
public function islike(){
$likes = CommentLike::where('comment_id', $this->id)->where('user_id', Auth::user()->id)->first();
return $likes->like;
}
<button class="btn-like">
<svg><use xlink:href="#like"></use></svg>
span class="like-count">{{ $comment->likes() }} - {{$comment->islike()}}</span>
</button>
<button class="btn-like dislike">
<svg><use xlink:href="#like"></use></svg>
<span class="dislike-count">{{ $comment->dislikes() }} - {{$comment->islike}}</span>
</button>
ErrorException
Undefined offset: 1
Answer the question
In order to leave comments, you need to log in
You can be sent to hell for this. Learn to enjoy relationships. It is impossible to receive data from the model as you receive them.
your code can at least look like this
class Comment extends Model
{
public function likes()
{
return $this->hasMany(CommentLike::class);
}
public function isLikeByUser($user = null)
{
if (!$user) {
return false;
}
$users = $this->likes->pluck('user_id');
return in_array($user->id, $users);
}
}
{{ $comment->isLikeByUser(Auth::user()) ? 1:0 }}
Uncle, if you make a call to first, then sometimes it returns null, get used to writing a type check through a colon. The code itself will become beautiful when you understand how powerful this thing is.
You like taking from what may not be. If the colon had written int, it would have cursed that the function would not have returned an int, I would have gone and corrected it. And so in the middle of the code somewhere someone is trying to tear out the first key and xs who it is.
And also a like comment, probably returning an array, you subtract from it ... A number. It's good that it works
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question