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

super_simon123's avatar

Get count from many-to-many where record doesn't exist?

I'm trying to display a simple count but I can't get my head around how I need to do it. I have three tables which include, users, hobbies and hobby_user as the swing table. A user can have many hobbies and a hobby can be shared by many users.

I'd like to be able to identify every user who doesn't have a hobby and output it as a count() assigned but I don't quite know how to do it.

User::model

public function hobbies()
    {
        return $this->belongsToMany(Hobby::class);
    }

Hobby::model

public function users()
    {
        return $this->belongsToMany(User::class);
    }

Where should I start?

The relationship is working as expected, with $user->hobbies->count() outputting as expected.

0 likes
2 replies
super_simon123's avatar

Ah you're a lifesaver! I took a look at doesntHave a couple of nights back, but typically it was 2am and clearly my eyes were dead.

Many thanks, this works perfectly.

Please or to participate in this conversation.