Fix - Ambiguous Column Eloquent Query Exception in Laravel

Ariel Mejia

October 14th, 2020 - 1 min read


Issue: An Eloquent Model with a relationship, both have a column that matches the same name


Let's check an example to show how to fix it

User Model:

public function teams()
{
    return $this->belongsToMany(Team::class);
}

Team Model

public function users()
{
    return $this->belongsToMany(User::class);
}

Then you can attach users to teams

Team::users()->attach(auth()->user());

And now you can get a collection of users by teams

$users = Team::users;

Ok here all fine, maybe you need to pass data to an API, and it's a better approach to get only the data that is required

$team = Team::first();
$team->users()->select(['name', 'email'])->get();

Here you would see an eloquent exception, this is because the User model has a column name and Team model could have a column name too,

Don't worry like all in Laravel is really easy, just be explicit with the table and the columns that you need

Team::users()->select(['users.name', 'users.email'])->get();

The same idea apply when you need to add a where method

Team::users()->where('users.email', $request->get('email'))->get();

Thanks for reading!


Ariel Mejia Illustration

Ariel Mejia

Laravel Senior Developer

Engineer with 7+ years of experience working in backend & frontend technologies
Open Source Maintainer of packages for Laravel community.

Stay up with Laravel

Sign up & get tips and tricks

You'll get monthly updates regarding my most recent articles and products.