Andrew
Andrew

Reputation: 55

Laravel eloquent relations won't work as supposed to when searching by id

I currently have 3 tables:

Posts:
-id
-text
-user_id
Comments:
-id
-text
-post_id
-user_id
Likes:
-id
-user_id
-comment_id

I want to get both Comments and Likes on those comments on my show() controller of Posts. This code in my Models seemed to work when using all(), however it completely breaks when im trying to search by id. It always returns all Posts, even though it should only get one.

class Posts extends Model
{
    public function comments(){
        return $this->hasMany('App\Models\Comments', 'post_id', 'id');
    }
    public function comment_likes(){
        return $this->hasManyThrough(
            '\App\CommentLikes',
            '\App\Models\Comments',
            'post_id', 'comment_id', 'id'
        );
    }
}

And controller code:

  public function show($id){
        $query =\App\Models\Posts::find($id)->with('comments')->with('comment_likes')->get();
        if(is_null($query)){
            return response()->json(['Not found'], 404);

        }
        return response()->json($query, 200);
    }

Is that even proper way of doing it?

Upvotes: 1

Views: 545

Answers (1)

mrhn
mrhn

Reputation: 18916

You are messing up query builders and models, the call sequence you have now will execute a new ->get() query from the model, therefor returning multiple posts.

This happens as ->find() executes a query, returns 1 element where the id is the parameter. This is now an Eloquent model, therefor you should not call with() and get() on this. You do that and this will execute a new query, therefor selecting all posts.

If you rearrange the order, it should work as expected.

\App\Models\Posts::with('comments')->with('comment_likes')->find($id)

Upvotes: 1

Related Questions