In this episode, we're diving into some refactoring work, especially around how we handle authorization. Up to now, we've been focusing on making sure our code does what we expect, mainly by writing tests first (test-driven development style), but our UI hasn't quite caught up yet. So, we start by actually hooking up the "Edit Book" feature in the UI, making sure the form submits a "PUT" request correctly. After making some updates, we check that everything is working as expected in the browser.
Once we're happy with that, we take a look at the authorization logic. Originally, we had some pretty manual checks in our controllers to make sure a user could only edit their own books. Instead of keeping this logic inline, we clean things up by moving it into a dedicated "policy." By creating a new BookPolicy, we centralize and simplify who can update what.
We then update the AuthServiceProvider to register this new policy, and switch our controllers over to use the new authorize
method. This all allows our controllers to be much cleaner. We check our work by running the tests, and they all still pass—a good sign that our changes didn't break anything!
As a nice bonus, switching to policies also gives us the chance to simplify our tests (and code) even further, since authorization is automatically handled before validation now. All in all, this refactor makes our app code more organized, readable, and secure, while maintaining confidence in how everything works through passing tests.