Check if post is liked by user. Laravel

I want to check if post was liked by a authenticated user when I display all posts of the users. This is my approach to this right now:

public function index(){
    $posts = Post::orderBy('created_at', 'desc')->get();
    $user = Auth::user();
    $liked = Post::with('user')
        ->whereHas('like', function ($query) use ($user) {
            $query->where('user_id', '=', $user->id);
        })->get();
    return view('index', compact('posts', 'liked'));
}

And when I do this in HTML:

@if($liked)
    <button class="[ btn btn-primary ]">
    <i class="fa fa-thumbs-o-up" aria-hidden="true"></i> You like this</button>
@else
    <a href="/patinka/{{$p->id}}" type="button" class="[ btn btn-default ]">
    <i class="fa fa-thumbs-o-up" aria-hidden="true"></i> Like</a>
@endif

I always get "You like this" even though I did not liked that post. Can someone tell me whats wrong with this code ?

Upvotes: 0

Views: 1687

Answers (1)

Mike Barwick
Mike Barwick

Reputation: 5367

First, let's ensure your relations are properly set.

Post model:

public function like() 
{ 
    return $this->HasMany('App\Like'); 
}

Like model

public function user() 
{ 
    return $this->hasOne('App\User', 'id', 'user_id'); 
}

Then combine your two Post calls together and run it like so:

$user_id = Auth::id();

$posts = Post::with(['like' => function ($like) use ($user_id) {
    return $like->whereHas('user', function ($user) use ($user_id) {
        $user->where('id', $user_id);
    })->get();
}])->get();

return view('index', compact('posts'));

Then in your view, you can do your check:

@foreach ($posts as $post)
    @if(count($post->like))
        ...
@endforeach

Upvotes: 1

Related Questions