In this episode, we're diving into deleting records—specifically, how to delete a post in Laravel. We kick things off by exploring the simplest method: accepting a post via route model binding and just calling delete()
on it. While this gets the job done, it has a big security hole—it doesn't check if the current user actually owns the post. Anyone could delete any post if they know the ID!
To work around this, we look at accessing the post via the user's relationship: grabbing only the authenticated user's posts and deleting the specific one. This not only cleans up our code but also makes sure users can only delete their own posts. We check out a few variations—getting the post with where()
or find()
, deleting in multiple steps, or condensing it all into a single, tidy line.
We also see what happens if a user tries to delete a post they don't own, and how to make our code handle that gracefully (without big errors crashing the page). Throughout, there's an emphasis on why you need to always think about authorization when deleting (or updating!) anything from your database.
All together, by the end of this video, you'll know a handful of ways to safely delete posts, and why you should always be thinking security-first!