In this episode, we finally jump in and start working on the friendships feature itself. We begin by setting up the friends
table (in a migration) to store the relationships between users. The friends
table uses two foreign keys: user_id
(the person sending the friend request) and friend_id
(the person receiving the request). To keep track of whether the request has been accepted or not, we add an accepted
column, using an integer instead of a boolean for some extra flexibility (and for Postgres compatibility).
Once the migration is set, we go to the User
model to define the Eloquent relationships. The friendships can go both ways (you can add someone, and someone can add you), so we create two relationships, friendsTo
(users you've sent requests to) and friendsFrom
(users who have sent you requests). We talk a bit about naming confusion and why we need both relationships because of the way the pivot table is set up.
Then, we add extra helper methods so you can easily fetch pending or accepted friend requests—whether that's people you've added but haven't accepted yet, or people who've added you and are waiting for you to accept. We set up scopes for pendingFriendsTo
, pendingFriendsFrom
, acceptedFriendsTo
, and acceptedFriendsFrom
.
By the end of this episode, you have all the Eloquent magic you need to manage, track, and query friend requests from both sides. Next episode, we'll actually test out adding friends and see how our relationships work in practice!