We're just referencing the relations we defined in the last step and scoping them by the pivot value.
Let's recap. We have have:
People we've added that haven't accepted
People we've added that have accepted
People who've added us that we haven't accepted
People who've added us that we have accepted
The problem with this two-sided relationship
If we want to see a list of our friends, we'd need to merge the people we've added, but also the people who've added us. This is because user_id in our pivot table is always the user who initiates the request.
Here's an example of the process.
Alex (user_id) adds Mabel (friend_id) as a friend
Mabel accepts the request (this sets accepted to true)
Alex can call acceptedFriendsTo and see Mabel, since it originated from him
Mabel can call acceptedFriendsFrom since she was added
But, Alex and Mabel do not have a common relationship they can use to see all of their friends
This is where friendship systems start to get confusing. How do we merge these relationships together?
Merging friends the bad way
We could create a method or accessor to merge the two collections from acceptedFriendsTo and acceptedFriendsFrom.
This new friends relationship works like a normal Eloquent relationship. You can now access all of your friends like this.
This will return a collection of friends. But, you could also paginate the results.
Great. We now have a 'real' relationship on our User model for either people we've added, or who have added us.
We've dealt with the relationships for friends here, but to learn how to add, accept, delete, decline and display friends, you might want to check out the course over on Codecourse which guides you through building the entire friendship system.