Updating the image in laravel 8 + inertia, validation error even the fields are filled

Viewed 558

I'm working with Laravel 8 + inertiajs. I can create a product with or without an image. But when I try to update a product and upload a new image, the validation looks for the required field even they're already filled.

here is my input field:

<input name="images" type="file" @input="form.images = $event.target.files[0]" />

in my vue:

props: {
        product: Object,
        categories: Array
    },
    data() {
        return {
            form: this.$inertia.form({
                name: this.product.name,
                category_id: this.product.category_id,
                description: this.product.description,
                date: this.product.date,
                images: this.product.images
            })
        }
    },       
    methods: {                      
        update() {
            this.form.put(this.route('products.update', this.product.id, {
                preserveState: true
            }))
        },            
    }
})

my update controller:

public function update(UpdateProductRequest $request, Product $product)
{
    $inputs = $request->validated();

    if ($request->hasFile('images')) {
        $filename = $request->images->getClientOriginalName();
        $file = $request->images->storeAs(('images'), $filename);
        $product->images = $file;
        $inputs['images'] = $product->images;
    }
     
    $product->name = $inputs['name'];
    $product->category_id = $inputs['category_id'];
    $product->description = $inputs['description'];
    $product->date = $inputs['date'];                 
            
    $product->update();

    session()->flash('flash.banner', 'Product Updated Successfuly');
    session()->flash('flash.bannerStyle', 'success');
    return redirect()->route('products.index');
}
1 Answers

multipart/form-data request is not natively supported in some languages for the put,patch or delete methods. The workaround here is to simply upload files using post instead.

Some frameworks, such as Laravel and Rails, support form method spoofing, which allows you to upload the files using post, but have the framework handle the request as a put or patch request. This is done by including a _method attribute in the data of your request.

    Inertia.post(`/users/${user.id}`, {
  _method: 'put',
  avatar: form.avatar,
})
Related