In this episode, we dive into how to actually attach files to a product after it's created. We start by acknowledging that just creating products isn't enough—we need a way to handle the files people want to associate with each product. So, the first thing we do is set up a new model and migration for our files table. This table will store each file's association with a product, the filename, and where it's saved on the file system.
We make sure that files are linked to products (not users), and set up the relationship so that if a product gets deleted, all its files are also automatically cleaned up. (Though, there’s a discussion about whether that’s always the best approach!)
Next, we wire up the code that takes the uploaded files, turns them into file models, and saves them in a batch—optimizing things so we're not hitting the database for every single file individually. You’ll see how we collect the files, process them with Laravel’s collection methods, store the actual files in the correct directory, and then bulk save them with a single saveMany
call on the product relationship.
Throughout, we debug a couple of common mistakes—like calling the wrong method to get the client’s original filename—but in the end, you’ll see how everything comes together. By the time we’re done, uploading multiple files for a product is smooth: files show up in your storage and the database stays in sync, all with minimal code. If you’re looking to let users upload and attach files cleanly to their products, this is the episode for you!