9

I tried to eager load a relation:

$tournaments = Tournament::with('numCompetitors')->latest()->paginate(config('constants.PAGINATION'));

My relation in Tournament returns an integer:

public function numCompetitors()
{
    return $this->competitors()->count(); // it returns 24
}

With that I get:

Call to a member function addEagerConstraints() on integer

I don't understand why is it failing.

Juliatzin
  • 18,455
  • 40
  • 166
  • 325

1 Answers1

18

You're doing it wrong. If you want to count relationship, use withCount() with properly defined relationship:

Tournament::withCount('competitors')->latest()->paginate(config('constants.PAGINATION'));

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.

https://laravel.com/docs/5.4/eloquent-relationships#counting-related-models

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279