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

noleafclover614@gmail.com's avatar

User global scope - ambiguous column 'id'

For some reason, I can't figure out how to retrieve what I want from my database using Eloquent. I have a User model and an Organization model, each connected by a belongsToMany relationship. The pivot table user_orgs that connects them has an additional column, indicating if the organization is the "primary" organization (is_primary) for the user.

Every time I query users, including the logged in user, I would like their primary organization name and ID to be accessible via attributes.

//User Model

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

//... 
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */

    public function organizations()
    {
        return $this->belongsToMany(Organization::class, 'user_orgs', 'user_id', 'organization_id')->withTimestamps()->withPivot('is_primary');
    }

//...

//Organization Model

class Organization extends Model
{
  
//... 

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */

    public function members()
    {
        return $this->belongsToMany(User::class, 'user_orgs', 'organization_id', 'user_id')
            ->withTimestamps();
    }

//...

My first thought was global scoping, which fails due to the following error:

//User Model

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

//... 

    public static function boot()
    {
        parent::boot();
        
        static::addGlobalScope('primaryOrg', function (Builder $builder) {
            $builder->join('user_orgs', 'users.id', '=', 'user_orgs.user_id')
                    ->join('organizations', 'organizations.id', '=', 'user_orgs.organization_id')
                    ->where('user_orgs.is_primary', '=', 1);
        });
        
    }

//...

Error:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `users` inner join `user_orgs` on `users`.`id` = `user_orgs`.`user_id` inner join `organizations` on `organizations`.`id` = `user_orgs`.`organization_id` where `id` = 100 and `user_orgs`.`is_primary` = 1 limit 1)
0 likes
5 replies
Snapey's avatar

The way I would start to approach this;

User model


public $with = ['primaryOrg'];

public function primaryOrg()
{
    return $this->belongsToMany(Organization::class, 'user_orgs', 'user_id', 'organization_id')->wherePivot('is_primary', 1);
}

However, I think this will still return a collection. An eloquent macro is probably needed to just grab the first, but my approach to this would be trial and error!

2 likes
noleafclover614@gmail.com's avatar

@Snapey I was moving in this direction! I eventually got to here, which does in fact still return a Collection:

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */

    public function primaryOrganization()
    {
        return $this->organizations()->wherePivot('is_primary', '=', 1);
    }

Can you point me towards some resources (Eloquent macros?) where I might learn how to grab just the first model from the collection?

noleafclover614@gmail.com's avatar

Thanks... I'll have to try to figure out how to make this work with a BelongsToMany relationship.

noleafclover614@gmail.com's avatar
Level 3

Looks like there may not be a way to do this with BelongsToMany:

https://github.com/laravel/framework/pull/17707#issuecomment-304985417

I think I may have solved this by doing a few things - hopefully this isn't too messy:

  1. Creating a global scope on my User model:
    public static function boot()
    {
        parent::boot();

        static::addGlobalScope('primaryOrg', function (Builder $builder) {
            $builder->with('primaryOrganization');
        });

    }
  1. Updating the $appends array:
protected $appends = ['primary_org_name', 'primary_org_id'];
  1. Added custom getters for each of the $appends array keys:
    /**
     * Get the Primary Organization Name attribute.
     * @param $value
     * @return mixed
     */
    protected function getPrimaryOrgNameAttribute($value)
    {
        return $this->primaryOrganization->first()->name;
    }

    /**
     * Get the Primary Organization Id attribute.
     * @param $value
     * @return mixed
     */
    protected function getPrimaryOrgIdAttribute($value)
    {
        return $this->primaryOrganization->first()->id;
    }

Please or to participate in this conversation.