labas GamePage visogero labas GamePage visogero - 1 year ago 95
PHP Question

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);
return view('index', compact('posts', 'liked'));

And when I do this in HTML:

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

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

Answer Source

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

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

Then in your view, you can do your check:

@foreach ($posts as $post)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download