0

trying to execute the following query on the FriendController

$friends = Auth::User()->friends;

and that is the friends function on the User model

public function friends()
{
    return $this->belongsToMany('App\Friend', 'friends', 'user_id', 'friend_id');
}

but on hitting the route i get the following error

Illuminate \ Database \ QueryException (42000) SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'friends' (SQL: select friends.*, friends.user_id as pivot_user_id, friends.friend_id as pivot_friend_id from friends inner join friends on friends.id = friends.friend_id where friends.user_id = 2)

Islam Mansour
  • 79
  • 1
  • 9

1 Answers1

0

Pivot tables should almost never have a model. If you're trying to use friends as a pivot table for two users, then the relationship should be referencing App\User, not App\Friend (or static which represents the current class).

public function friends()
{
    return $this->belongsToMany(static::class, 'friends', 'user_id', 'friend_id');
}

You'd want to return a collection of users, not "friends" since friend isn't an entity, it's a relationship.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95