droplister's avatar

Upload Multiple Files and Relate them to Post Model

I have a VueJS component that is a "Create Post Form". The trouble I am having is with file inputs and getting the file data in the same request as the Post data.

I have a method ready to handle image uploads and it works with a plain html form, but file inputs are a special case in VueJS.

    /**
     * https://github.com/spatie/laravel-medialibrary
     */
    public function storeImages(Request $request)
    {
        if($request->has('images'))
        {
            foreach($request->file('images') as $image)
            {
                $this->addMedia($image)->toMediaCollection('images');
            }
        }
    }

Unlike my code, the tutorials and repositories I have found handle the file input independently of any related models. I am looking for a tutorial or solution that will let me relate the uploaded images with the post that is being created at the same time.

I have seen some mention of appending a blob to the form, which seems closest to what I am trying to do. Maybe there is just a better way to do it. Any insights or links appreciated!

0 likes
2 replies
droplister's avatar
droplister
OP
Best Answer
Level 1

Okay, I think I have it working now. Simplified component for reference.


<template>
    <input type="file" multiple @change="onFileChange" />
</template>

<script>
    export default {
        data() {
            return {
                postFormData: new FormData(),
            };
        },

        methods: {
            onFileChange(event) {
                for(var key in event.target.files){
                    this.postFormData.append('images[]', event.target.files[key]);
                }
            },
            addPost() {
                axios.post('/api/v1/post', this.postFormData)
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
            }
        }
    }
</script>


1 like
droplister's avatar

Added a delete images[] on the event, in case someone selects new images after selecting a different set.

            onFileChange(event) {
                this.postFormData.delete('images[]');
                for(var key in event.target.files){
                    this.postFormData.append('images[]', event.target.files[key]);
                }
            },

Please or to participate in this conversation.