In this episode, we're focusing on fixing up how our app handles friends, before we move on to building the feed that shows all the books our friends are reading, have read, or want to read.
Currently, the friend relationship is being managed by merging together two collections: accepted friends of mine
and accepted friends of
. While this works, it's not a true relationship in Laravel, which makes things like pagination a pain. So we set out to fix this and make the friends relationship work properly and efficiently.
We introduce the Laravel Merged Relations package, which lets us create a SQL view that combines both directions of a friendship into a single relationship. After installing the package, we update our database migrations and set up the view. Then, we update our user model to use the new merged relationship. Throughout, we keep an eye on our tests to make sure nothing breaks.
Along the way, we discover a bug: deleting a friend only works in one direction! If you remove someone as a friend, it's only reflected one way, not from both users' perspectives. We fix this so that removing a friend works from either side, and update our tests to cover this behavior.
After all that, we check everything is working, all tests are passing, and now we have a robust friends system. This sets us up perfectly for the next step: building the feed that brings all of our friends' books together.