ahmadbadpey's avatar

Illegal offset type error on fetching a relations to self class in laravel

My User model is like this :

class User extends Authenticatable
{
    protected $primaryKey = 'user_id';
    protected $fillable = [
        'username',
        'password',
        'name',
        'family',
        'supervisor'
    ];

    public function children()
    {
        return $this->hasMany(\App\User::class, 'supervisor', 'user_id')->with('children');
    }

}

As you can see there a supervisor column that specify parent of a user.

Now to fetch all children of user models that have supervisor= null, I wrote this :

return User::with('children')->whereNull('supervisor')->get();

but it return this error always :

PHP Warning:  Illegal offset type in D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\HasOneOrMany.php on line 168

Table users have these data :

+---------+-------------+---------+--------------+------------+
| user_id |  username   |  name   |    family    | supervisor |
+---------+-------------+---------+--------------+------------+
|       1 | 09139616246 | ahmad   | badpey       | null       |
|       7 | alinasiri   | ali     | nasiri arani | 1          |
|       8 | zahedi      | mostafa | zahedi       | 1          |
|       9 | hsan        | hasan   | ghanati      | 8          |
+---------+-------------+---------+--------------+------------+

Even I tried solution here but same error occurred.

Update :

I found that problem is that I have a accessor same name supervisor attribute like this :

public function getSupervisorAttribute($value)
{
    return is_null($value) ? null : User::select('user_id', 'name', 'family')->find($value);
}

I added that because I want to return supervisor user as an object. But now in this case, what do I do ?

0 likes
1 reply
bobbybouwmann's avatar

Your relationship is invalid as well

public function children()
{
    return $this->hasMany(\App\User::class, 'supervisor', 'user_id')->with('children');
}

Should be

public function children()
{
    return $this->hasMany(\App\User::class, 'supervisor', 'user_id');
}

A relationship should always return a relation object, as far as I know you shouldn't be calling with on that relationship!

Please or to participate in this conversation.