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

hamidali's avatar

Append Relation Count while using select in eloquent query

So i have a query where i want to select specific columns and relation count on a model.

Something like this

Post::withCount('comments')->select('title', 'content')->get();

Now when I use select in the query comments_count is no longer available. There is $appends option on the model where I can do something like $appends = ['comments_count'] on the Post model but it will not work. Any idea how to append the data and use the select on model while querying using eloquent.

there is $withCount option on the model as well but it will lazy load while querying comments with post (i.e. inverse relation query).

0 likes
3 replies
kevinbui's avatar

Well, I believe it got to be in this order:

Post::select('title', 'content')->withCount('comments')->get();

withCount is more like a query scope than a customer attribute. So if you want to have that in all the queries, I think you have to use a global scope.

MuhammadHHassan's avatar
Level 4

I think you've asked two questions here

1- Why the key you added to $append does not show? Because to append a property that doesn't have a column in the model's table you need to define an accessor first. So in this case you need to define a method with the name getCommentsCountAttribute that returns the count. and it will only show when the model is converted to array or JSON

2- How to use select and withCount is actually mentioned here in the documentation. You must call select first

Martin Lurther's avatar

I think, this one is right 1- Why the key you added to $append does not show? Because to append a property that doesn't have a column in the model's table you need to define an accessor first. So in this case you need to define a method with the name getCommentsCountAttribute that returns the count. and it will only show when the model is converted to array or JSON

Please or to participate in this conversation.