using nuxtjs and filepond to send images to a laravel API

Viewed 343

I have a nuxt frontend using the vue-filepond adapter, users have the option to upload images with there post. This is then send to a laravel API that will handle the request.

<client-only>
  <file-pond
    name="image"
    ref="pond"
    class="filepond"
    :allow-multiple="false"
    accepted-file-types="image/jpeg, image/png"
    server="http://127.0.0.1:8000/api/posts"
    allowRevert="false"
    :files="form.image"
  />
</client-only>

using mostly default filepond options,

data() {
  return {
    errors: [],

    form: {
      title: '',
      content: '',
      image: [],
    }
  }
},

Data is uploaded to the api like so

methods: {
  createPost() {
    this.$axios.$post('http://127.0.0.1:8000/api/posts', this.form)

    this.$toast.show({
      type: 'success',
      title: 'Success',
      message: 'Your post has been created'
    })
  }
}

Now since filePond is async the file is uploaded earlier then my form when I post it.

so in the laravel part

public function store(Request $request): void
{
    if ($request->hasFile('image')) {
        $path = Storage::putFile('avatars', $request->file('image'));
    }

    $request->validate([
        'title' => 'required|string|max:24',
        'content' => 'required|string|max:254',
        'image' => 'nullable|image'
    ]);

    Post::create([
        'title' => $request->get('title'),
        'slug' => Str::slug($request->get('title'), '-'),
        'content' => $request->get('content'),
        'image' => $path ?? null
    ]);
}

The image would be stored, but if I click submit on my form to upload a title and some content the ìmage part in the Post::create method is always NULL.

How can I make it so that filePond is not uploaded async anymore? so that when I hit submit on my form the title , content and image are all uploaded equally

1 Answers

Figured it out thanks to kissu and reading through filePond's docs.

const file = this.$refs.pond.getFiles()[0].file

const data = new FormData()

data.append('title', this.form.title)
data.append('content', this.form.content)
data.append('image', file)

this.$axios.$post('http://127.0.0.1:8000/api/posts', data)

and in your backend (laravel in my case)

if ($request->hasFile('image') && $request->file('image')->isValid()) {
  $post->addMediaFromRequest('image')->toMediaCollection('image');
}
Related