In this episode, we focus on a core feature of any social app: getting an accurate list of a user's friends. At first, we look at how our current data setup (with two relationships: "friends to" and "friends from") only tells half the story depending on which way the friendship was initiated. Just picking one direction won't give you a full, accurate list of friends.
To explore the problem, we try to just grab one relationship and loop over it, seeing how it only shows friends from one side. Then, we experiment with merging the two collections together in the model. This technically works for simple outputs, but we quickly run into issues—like not being able to paginate, or do more advanced queries and eager loading.
To solve this properly, we introduce the Laravel Merged Relations package. This handy tool lets us combine these two friend relationships at the database level with an SQL view, giving us a single relationship that behaves just like a typical Eloquent relationship. We walk through installing the package, creating a migration for the view, and updating our code to use this new merged friends list—even showing how you can now easily build out paginated lists and fetch related data through this setup.
To finish, we do a quick test by adding another user and making sure everything works perfectly for different friend directions. Now, we've got a bulletproof way to get all of a user's friends—no matter who added who!
Next up: We'll look at how to handle unfriending a user.