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

KHAN's avatar
Level 4

How to get the count of a hasMany relationship within the Model

Hey,

Im trying to get the count of a hasMany relationship. In my scenario Event has many Reservations

Controller

$event = EventModel::find(1);
return $event->rsvps()->count();

This works perfectly it returns the count for me. However i want to extract this and put it as a function within my Model class, so i can check whether the event is full.

Model

    public function isFull()
    {
        $max = $this->max_users;
        $current = $this->rsvps()->count();
        return $isFull = ($max === $current) ? true : false;
    }

But this is returning an exception

LogicException in Model.php line 2721:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
0 likes
2 replies
JarekTkaczyk's avatar

@KHAN It seems you have max_users() method, but you're calling it as property max_users (or trying to call $model->isFull as a property).

1 like
KHAN's avatar
KHAN
OP
Best Answer
Level 4

Actually max_users is a field in the table. I dont now why but this is working now anyway.

Please or to participate in this conversation.