


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
public function teams()
{
return $this->belongsToMany(Team::class);
}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!
Sign up & get tips and tricks
You'll get monthly updates regarding my most recent articles and products.