5 months ago

Upload a file to a model ID subdir

Posted 5 months ago by ihorvorotnov

Hi everyone! Im creating Exercises in Nova and use native File and Image fields to handle uploads. However, Id like the files to be stored in a sub directory with model ID:

- public
  - media
    - {id}
      - video.mp4
      - image.jpeg

This works fine when updating an existing model (the ID is already available), but the files are uploaded to base upload path public/media for new Exercises. This means model ID is not available during file upload yet.

Is it possible to achieve this in any other way? How would you do it, e.g.:

  • can you somehow queue uploads (which would be good to speed things up for admins too)? Queued tasks should be able to access model ID, right? Couldnt find any docs about queues in Nova though.
  • listen to created event, get the ID, create dir, move files and update database fields? Sounds doable but quite some extra work.
  • write custom store procedures for media files and handle it there? Will it run after the model is created or still before saving it to the database so no ID is available?
  • just replace the ID with some unique string that can be generated upfront and appended to a path instead? How would you store it so its accessible for subsequent edits? Get it from saved media file path every time or store as a separate field in database?

Im new to both Laravel and Nova and dont know the best practices yet (unless they are covered in one of the videos here). Would appreciate any help/advice on this.

P.S.: I will also generate intermediate sizes for the image later using Intervention package, tried couple things and the best idea Ive came up with is to handle it on saved and deleted model events. Am I doing it wrong here too?

Please sign in or create an account to participate in this conversation.