In this episode, we deal with a common problem: what should happen with a user's comments when they delete their own account? First, we look at how things are set up right now—when a user is deleted, the user_id
on their comments is set to null
, but the comments themselves stick around and aren’t marked as deleted. This causes some issues when the app later tries to load details like the user's avatar for those comments, leading to errors.
To demonstrate the problem, we create some comments, delete the user, and see firsthand what goes wrong. After clearing the database and going through the user account deletion again, we set out to fix things up properly.
We jump into the User model and use Eloquent's model events to hook into the deletion process, setting up a booted
method. Here, before the user record is actually deleted, we find all the user’s comments and soft-delete them (instead of just orphaning them or wiping them out). This cleanup makes sure that when a user goes, their comments are safely marked as deleted, keeping the database tidy and the app from running into null pointer errors.
Finally, we test this new behavior by creating a user with comments, deleting the account, and confirming that the user’s comments are indeed all soft deleted. Problem solved!