0

I'm making posts for my website and now I want people able to like the post. But when they like the post (if there are 0 likes) you see one empty heart. But when multiple people likes the post there will be more hearts.

Here is my code

@foreach($post->likes as $likes)
    @if($likes->where('user_id', Auth::User()->id))
        <i onclick="window.location.href = '/blog/like/{{ $post->id }}';"
           class="fa fa-heart liked"></i>
    @else
        <i onclick="window.location.href = '/blog/like/{{ $post->id }}';"
           class="far fa-heart"></i>
    @endif
@endforeach

In the code above, you have a i class with 'liked' in it. I want one of that item on my blade and not multiple. Can somebody help me?

enter image description here

Must be one heart

3
  • Just to clarify, are you showing all likes as an <i> element, if you are the one liking, it should have 'liked' class? Commented Mar 26, 2020 at 13:01
  • I've edited what I mean Commented Mar 26, 2020 at 13:03
  • 1
    You could create a custom attribute of Post which checks if the user has liked it, then it's a simple if statement and not looping through all likes. Commented Mar 26, 2020 at 13:05

1 Answer 1

1
                    @if(count($post->likes) !== 0)
                        <i onclick="window.location.href = '/blog/like/{{ $post->id }}';"
                           class="@if($post->likes->contains('user_id', Auth::User()->id) === true)fa fa-heart liked @else far fa-heart @endif"></i>
                    @else
                        <i onclick="window.location.href = '/blog/like/{{ $post->id }}';"
                           class="far fa-heart"></i>
                    @endif

I have fixed it my doing this above ^^ I removed the foreach and add the contains() method and check if it is true now it works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.