0

I have 2 model: User and Team. - A user belongs to a team. - A team has many users.

And here is my User model.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable {

    use Notifiable, HasRole;

    protected $guarded = [];

    protected $with = ['team', 'role'];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function team()
    {
        return $this->belongsTo(Team::class);
    }
}

Team model:

class Team extends Model {

    protected $with = ['leader'];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('membersCount', function ($builder) {
            $builder->withCount('members');
        });
    }

    public function leader()
    {
        return $this->belongsTo(User::class, 'leader_id');
    }

    public function members()
    {
        return $this->hasMany(User::class);
    }
}

When I tried to eager load team in User model by using protected $with = ['team'];, it ends up with a error

Maximum function nesting level of '512' reached, aborting!

Can anyone help me? Thank you!

user3118789
  • 589
  • 2
  • 12
  • 26
  • 3
    Looks like you've created a recursive dependency between team and users, though can't say for sure not knowing how eloquent works internally. – Jonnix Oct 24 '18 at 08:12
  • 1
    try to change `leader()` method calling `hasOne` against `belongsTo` – Artem Ilchenko Oct 24 '18 at 08:18
  • @JonStirling yes, you're right. My app need to be like that. A user belongs a team and a team have to have a leader (user_id). I don't know how can I handle it. @ArtemIlchenko it doesn't work, because my `users` table never has `leader_id` field – user3118789 Oct 24 '18 at 08:21

1 Answers1

-2

Putting the below in my php.ini worked for me.
Basically you need to increase the nesting level.

xdebug.max_nesting_level = 1024
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Debashis Prusty
  • 393
  • 2
  • 6