Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

murilo's avatar
Level 10

Select Query Posts with Likes

Hello , I have a question , I am developing a website like a facebook . It will have POSTS and a User can LIKE those posts ,

So a user can search all those posts , if this post is LIKED ( this user has given a like ) , so it has to show that this post is liked .

The like and POST is related by Many to MAny relation ship .

Will be like that -

POST MODEL

 // LIKE
    public function Like() {
        return $this->belongsToMany(User::class , 'user_post_likeble' , 'post_id'  , 'user_id');
    }


POST QUERY RESULT ->


  $result  = Prop::select(['id', 'title' , 'description'])

    // LIKED , IT SAYS TRUE OR FALSE
            ->with([ 'Like' => function($query) {
                // I dont know how could I make the relation ship here to say TRUE for those one that has relation chip / FALSE for those one that dont has relation ship .                 

            } ])->get()



Thanks .

0 likes
7 replies
lostdreamer_nl's avatar

it's easier (on your code as well later) if you keep your method names in someMethodName syntax, and keep the singular and plural names the same as their return results.

So I'd rename the method Like to likes

Also, remember that you will now be coding like foreach($post->likes as $like) but the $like is actually a user object ?

I would do it like this:

// Post.php
    public function likes() {
        return $this->hasMany(Like::class);
    }
    public function likedBy() {
        return $this->belongsToMany(User::class , 'user_post_likeble' , 'post_id'  , 'user_id');
    }
    public function getIsLikedAttribute() 
    {
        return $this->likes->where('user_id', auth()->id())->count() > 0;
    }

// Like.php
    protected $table = 'user_post_likeble';

    public function post() {
        return $this->belongsTo(Post::class);
    }
    public function user() {
        return $this->belongsTo(User::class);
    }

// User.php
    public function likedPosts() {
        return $this->belongsToMany(Post::class , 'user_post_likeble' , 'user_id', 'post_id');
    }
    public function likes() {
        return $this->hasMany(Like::class);
    }

So now you have:

  • Post, Like and User objects
  • Posts haveMany Likes, and are likedBy many Users.
  • Likes belong to both a User and a Post.
  • Users have many likedPosts and many Likes.

And you should be able to do some stuff like:

// gets a single post with all likes and the associated user accounts
$post = Post::with('likes.user')->find(1);
// Or if you want a list of a few posts, and foreach see if the current user has liked this post
$posts = Post::with('liked')->limit(10)->get();
foreach($posts as $post) {
    echo $post->id ." = ". $post->is_liked ."\r\n";
}

Getting the posts that the current user liked is even easier:

$likedPosts = auth()->user()->likedPosts;
dd($likedPosts->toArray());
murilo's avatar
Level 10

Thanks very mutch for the help @lostdreamer_nl and @drfraker , in both examples it uses that -

foreach($posts as $post) {
    echo $post->id ." = ". $post->is_liked ."\r\n";
}

I can not make like that , I am using JSON REQUEST , I am not displaying on the VIEW , so I need to bring all those results like this in my CONTROLLER becose I am using all those results in VUE Js ->


 $result  = Prop::select(['id', 'title' , 'description'])

    // LIKED , IT SAYS TRUE OR FALSE
            ->with([ 'Like' => function($query) { 
                       
            } ])->get()

  return response()->json($result) .

lostdreamer_nl's avatar

So? Just change it into Vue / javascript.....

$posts = Post::with('liked')->limit(10)->get();

return response()->json($posts);

// in Vue model:
// posts should be gotten via ajax request
data: {
    posts: posts
},

// in Vue template:
<ul>
    <li v-for="post in posts">
        {{ post.id }} = {{ post.is_liked }}
    </li>
</ul>

Still tring to figure out why you are talking about a Post model, while you are using a Prop model though....

murilo's avatar
Level 10

Thanks , @lostdreamer_nl , It shows like that - I can do like this ->


 // WITH LIKES
            ->with([ 'likes' => function($query) {
                
                         $query->where('user_id', '=', $this->user->id);
                 
            } ])


It shows like that ->

[{ "id":1 , "title":title , "description":post_description ,"likes":[{"post_id":44,"user_id":22}] , .... } ,
  { "id":2 , "title":other title , "description":other post_description ,"likes":[] , .... }]

can I make something to shows TRUE or FALSE instead ? like this -

[{ "id":1 , "title":title , "description":post_description ,"likes":true , .... } ,
  { "id":2 , "title":other title , "description":other post_description ,"likes":false , .... }]

lostdreamer_nl's avatar
Level 53

the easiest way is to add a mutator to the Post model (as in my previous example)

    public function getIsLikedAttribute() 
    {
        return $this->likes->where('user_id', auth()->id())->count() > 0;
    }

Also add it in the Post model $appends list:

Class Post extends Model 
{
    protected $appends = ['is_liked'];
}

Now, whenever you have a Post (and you have gotten the post with all of it's likes, or just the current user's) you can check if the current user has liked this post by checking $post->is_liked

So:

$posts =  Post::limit(10)->with([ 'likes' => function($query) {
    $query->where('user_id', '=', $this->user->id);
}])->get;
return response()->json($posts);

Now all the posts will have an is_liked property in there that will say true / false.

Please or to participate in this conversation.