In this episode, we dive into building the feature that lets users create (or store) a book in the application––moving on from our earlier authentication and basic Pest testing setup. Instead of starting with the form, we focus directly on setting up and testing the backend logic.
First, we plan out our test for the book creation endpoint, thinking about authentication and ensuring only signed-in users can create books. Then, we scaffold a new controller and set up the relevant routes. After wiring up some basic logic to get the authentication working properly, we move on to structuring our database: setting up the books
table (with title and author fields) and the crucial pivot table book_user
to link users to books with an extra status
field for things like "want to read", etc.
We also set up and implement model relationships to handle this many-to-many linkage, making sure that storing a new book also stores the correct data in both the books
table and the book_user
pivot table, including the status. Along the way, we troubleshoot common stumbling blocks (like remembering to set fillable properties and adding the necessary pivot data).
Testing plays a huge part throughout. We build out Pest tests to check both the database records and validation rules (making sure required fields like title, author, and status are enforced). We also talk about handy Pest features like skip
for temporarily ignoring tests, and how to DRY up our tests using before-each hooks for shared setup.
By the end of this episode, we've got a fully working backend for creating and tying books to users with statuses, and solid tests to prove it. Next time, we'll look at polishing our status validation, making sure only expected statuses are accepted using a custom class. It’s hands-on and full of practical testing and Laravel relationship tips!