In this episode, we dig into a common problem when handling file uploads in Laravel: keeping users’ uploaded files separated, so things don’t get messy and it’s easy to clean up if a user leaves your app.
We start by looking at the default behavior, which dumps all files in one folder and isn’t ideal. Instead, we want to automatically sort uploads into a folder per user. The main focus here is using Amazon S3 as the example storage, but the method works with any filesystem backend.
First, we spend a few minutes getting S3 all set up in a Laravel project, configuring credentials and the disk driver. Then, we look at the most basic way of prefixing uploads with the user's ID – but doing this manually everywhere quickly turns into a hassle.
The real solution comes in leveraging Laravel's filesystem manager and middleware. You’ll learn how to write custom middleware that programmatically tweaks the disk configuration at runtime. This way, when a user is signed in, any file uploads using a special disk will end up in their own folder, cleanly separated. We walk through how to write and register this middleware, how to inject the FileSystemManager, and how to clone and adjust the config per request instead of doing a global override.
Finally, we test it with both S3 and local storage, showing that the pattern works regardless of the backend driver. By the end of this episode, you'll have a reusable, automatic way in Laravel to keep each user's files neatly organized and easy to manage.