M
M
Maxim2019-09-22 17:00:07
Laravel
Maxim, 2019-09-22 17:00:07

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;
    }

when posting comments
<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>

I want to display the value, but writes
ErrorException
Undefined offset: 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin B., 2019-09-23
@Kostik_1993

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);
    }
}

In the controller, it is necessary to request likes all at once, this optimizes the number of requests to the database to 2 instead of your n + 1. And already in the template, you can simply request by user
{{ $comment->isLikeByUser(Auth::user()) ? 1:0 }}

G
Grigory Vasilkov, 2019-09-23
@gzhegow

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 question

Ask a Question

731 491 924 answers to any question