Best way to handle file uploads before model is created?
lets say you have article form, where one write a post and can upload A multiple images before he save the article.
how you handle the images upload? because while the upload is going on the Article is not created yet, than you cant assign the photo to uncreate article.
what I did till now is give any new article a temporary random id, on uploading give the images the random id, on saving the article take all the photos who belong to this random id, and move them to the new created article.
but it's kind of hacky solution, would love to hear
@boynet Instead of issuing a temporary ID, save a real model instance with any data you have so far and assign the photos to it. When the new article itself is submitted just update the existing database record.
If you are concerned about the user not finally submitting the article then you can assign a value/column "submitted" or "visible" ... that defaults to false and is set to true when the article has been submitted. Only display articles where that value is set to true.
You can even have some kind of garbage collection like a job that once a day removes all records with that value set to false that are older than a day.
@skliche thanks I hoped that there is a better solution, as now before saving I need to trigger all the validations rules, and I don't want to raise error before the user finished, I can skip the validation but then there is a unvalidated data. it's still kinda hacky.
but I understand there is probably no better solution
@boynet Are you wanting to only save the Article if the images succeed in uploading? Or, would you want to save the Article even if the images fail for some reason?
What @skliche suggests is a good approach. You could even make thew submitted or visible a global scope if you know you always only want to show Articles that have photos uploaded.
@boynet Yes, there would be unvalidated data in the database, but you can still validate the data when the user actually wants to submit the article. Until then, the article is clearly marked as not validated. You could reflect that state by calling the column validated or dirty instead of visible or have a status column.
Just keep in mind that some actions might not be allowed for those records. As @etkimbia mentioned scopes come in handy and you could even use authorization guards to ensure that.
If you want to avoid all that you could force the user to submit the article before they are allowed to upload images. I think that's how the problem was handled in the series "create project flyer with me".
To speed up my development I made the form a two stage process. Create the article then allow the image upload. Using VueJS it was pretty seamless and didn't require any browser reloading.