Jens Bouma
Jens Bouma

Reputation: 149

PHP foreach loop gets 2 instead of one laravel blade

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

Upvotes: 0

Views: 141

Answers (1)

Jens Bouma
Jens Bouma

Reputation: 149

                    @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.

Upvotes: 1

Related Questions