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

m_pro_m's avatar

withCount model property

Hey guys,

I can not find any information on protected $withCount = []; property in eloquent models. It should append relation count to attributes but it totally crashes my site. It skips laravel's error handler and throws error 500 in browser. Tinker quits immediately.

This is an example of how I used it:

class Post extends Model {
    protected $withCount = ['comments'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

Btw, withCount() query builder's method works just fine.

0 likes
3 replies
Jaytee's avatar

I've personally never heard of the withCount() property, but I did a little research, and it appears that it doesn't work??

As an alternative, you can use the appends property and then setup an accessor.

protected $appends = ['commentsCount'];

public function getCommentsCountAttribute()
{
    return $this->comments()->count();
}

Now each time you get an instance of the Post model, there will be a property appended called commentsCount that you can directly access.

$post->commentsCount

TimothePearce's avatar

$withCount isn't documented but easy to use after reading the source code.

After defining the relationships, you can access the count attribute as following $this->${yourRelationship}_count

In your case, you can access the number of comments with: $this->comments_count.

1 like

Please or to participate in this conversation.