phplaraveleloquent

Is it possible to setup a permanent property on a Laravel Eloquent model using withCount()?


I have a Laravel Eloquent model called Team that has a hasMany relationship to users. Is it possible to easily setup a user_count property that is permanently on a Team model? or do I always need to re-query the team with withCount(['users']) in the chain? As it stands right now, I can use $this->users()->count() but that is a lot less efficient than being able to use something like select count(id) as user_count from users (which I assume withCount() does).

Here's a truncated example of the class with the relevant bits.

class Team extends JetstreamTeam {
    public function user_count() {
        return $this->users()->count();
    }
}

Solution

  • If you want to automatically add the withCount() query, you can add the $withCount property.

    class Team extends JetstreamTeam
    {
    
        protected $fillable = [....];
    
        protected $withCount = ['users'];
    
    }
    

    Then you may call the $team->users_count without executing the aggregate function.

    This is not in the documentation, but you can find it in the Laravel source code here. The nearest mention I can find is in this section of the laravel docs.