how can i check if a user is already liking a post or not?

To avoid multiple queries, you could use an array of post ID’s and check the existence of the random posts in that array:

$userPostLikes = $user->likes->pluck('post_id');

$posts = Post::inRandomOrder()->get();

@foreach ($posts as post)

  @if(in_array($post->id, $userPostLikes)) 
     user likes post
  @else
     user doesn't likes post
  @endif

@endforeach

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top