Ad

Load All Posts And Check If The Post Is Liked Or Not In Laravel

I have a Post model and a Like model.

When I go a user page, I can see all the posts he liked. Now, I want to indicate a small icon if a post is already liked by the logged in user who is visiting a user page.

This is how I select the liked posts of the user (not the logged user but the profile owner):

$likesPost = Post::with('user')->join('likes', function ($join) use ($user) {
    $join->on('likes.likeable_id', '=', 'id')->where('likes.user_id', '=', $user->id)->where('likes.likeable_type','=', Post::class);
})->get();

Now I want to also check if the authenticated user has already liked this post or not along with this query. I've tried many things but I'm not sure how I should approach this problem. I'm using polymorphic relations.

Ad

Answer

First, I would change up your initial query a little bit. I'd get the posts liked by the user like this (assuming the Post has a likes relationship):

$profileLikedPosts = Post::whereHas('likes', function($query) use ($user) {
        return $query->where('user_id', $user->id);
    })
    ->get();

Next, you can get the liked posts of the currently logged in user like this:

// The "whereIn" just limits the results to those posts already retrieved
// for the profile user. Not required, but gives a little performance boost
// if this collection doesn't need the non-profile-liked posts.

$authUser = Auth::user();
$authLikedPosts = Post::whereHas('likes', function($query) use ($authUser) {
        return $query->where('user_id', $authUser->id);
    })
    ->whereIn('id', $profileLikedPosts->lists('id'))
    ->get();

Now, in your blade template, as you loop through the liked posts for the profile user ($profileLikedPosts), you can use the Collection contains() method to check if the post was also liked by the logged in user:

@foreach ($profileLikedPosts as $post)
    // ...
    @if ($authLikedPosts->contains('id', $post->id))
        // this post is liked by both; show your icon
    @endif
    // ...
@endforeach
Ad
source: stackoverflow.com
Ad