I’m working on a mini chat system and my main model is User.
Each User has many Contacts. A Contact is just another User in the system. A User can send an add request to the Contact which upon approval, the two parties can communicate.
My Approach was creating a pivot table contacts which will hold two foreign keys of the contact users at both ends; user_id which is the one making the contact request, and contact_id the other user of the contact.
This is my implementation of the relationship inside of the User Model:
public function contacts(): belongsToMany
{
return $this->belongsToMany(User::class,'contacts', 'user_id', 'contact_id')
->withTimestamps();
}
The problem with this approach is that if UserA sends a contact request to UserB and approves it, then I try to get UserA contacts I get exactly what I expect, UserB .
UserA->contacts; // Returns UserB
But if I do this:
UserB->contacts; // Returns Nothing
UserB doesn’t recognize UserA.
How do I solve this problem?
I understand it appears because belongsToMany always looks for contact_id but never user_id. I tried replicating every Contact row in my DB but the second copy has swapped user_id with contact_id and it works as expected, except that I think this approach violates the DRY principle and doesn’t seem clean.
4