1
votes

I'm struggling to upload an image and several text/numeric data fields to a MySQL DB with Vue, Laravel, and Axios.

Here's the method in my Vue component:

 addProductToShop() {
      const imageData = this.$refs.inputUpload.files[0];
      const formData = new FormData();
      formData.append("image", imageData);

      axios
        .post("api/createProduct", {
          formData,
          ...this.newProduct
        })
        .then(res => {
          console.log(res);
        });
    },

And here's the method in my Laravel controller:

public function create(Request $request)
{
    $product = Product::create([
        'name' => $request->name,
        'price' => $request->price,
        'amountInStock' => $request->amountInStock,
        'image' => $request->image->store('ProductImages', 'public'),
        'measuringUnitId' => $request->measuringUnitId,
        'categoryId' => $request->categoryId,
        'shopId' => $request->shopId,
    ]);

    return response()->json([
        'status' => 'success',
        'message' => 'Product added seccessfully',
        'product' => $product
    ], 200);
}

Here's the request body in telescope:

{
  "formData": [],
  "name": "111",
  "categoryId": null,
  "price": "111",
  "amountInStock": "111",
  "measuringUnitId": 2,
  "visability": true
}

And here's the error that i'm getting: Call to a member function store() on null

I've tried adding multi-form data headers:

   headers: {
        'Content-Type': 'multipart/form-data'
    }

However, they generated this error: Missing boundary in multipart/form-data POST data in Unknown on line 0 So, they seem obsolete now, because axios knows the corrent formData based on the FormData().

Can someone point out what am i doing wrong? Thanks in advance!

1

1 Answers

1
votes

Error here:

'image' => $request->image->store('ProductImages', 'public')

Correct way:

'image' => $request->file('image')->store('ProductImages', 'public')