最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - LaravelInertia jsReact js PUT Request Form Data Not Fully Received on Update When Including Image Upload - Stack Overf

programmeradmin3浏览0评论

I'm facing a strange issue in my Laravel Inertia.js project. I can successfully create new 'Ville' resources, including image uploads. Updates also work fine if I don't upload a new image. However, when I try to update a 'Ville' and include a new image, it seems like the entire form data isn't being sent to Laravel correctly, leading to validation failures.

Specifically, Laravel throws a "The nom field is required" error, even though the 'nom' field is definitely part of the FormData being sent.

Here's the React component (Edit.jsx) using Inertia.js useForm for the update:

import { useForm } from '@inertiajs/react';
// ... imports ...

export default function Edit({ auth, ville }) {
    // ... (YearlyDataInput, DYNAMIC_FIELDS, etc. -  as in my code) ...

    const { data, setData, put, processing, errors } = useForm({
        nom: ville.nom || '',
        region: ville.region || '',
        geographie: ville.geographie || '',
        histoire: ville.histoire || '',
        image: null,
        nombre_annonces_analysees: ville.nombre_annonces_analysees || 0,
        // ... other fields ...
        ...Object.fromEntries(DYNAMIC_FIELDS.map(field => [field.name, ville[field.name] || {}])),
    });

    const handleSubmit = (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('_method', 'PUT'); // Explicitly setting PUT method
        Object.entries(data).forEach(([key, value]) => {
            if (key === "image" && value instanceof File) {
                formData.append(key, value);
            } else if (typeof value === "object" && value !== null) {
                formData.append(key, JSON.stringify(value));
            } else if (value !== null && value !== undefined) {
                formData.append(key, value);
            }
        });
        console.log("FormData contents:");
        for (const pair of formData.entries()) {
            console.log(pair[0]+ ', ', pair[1]);
        }
        put(route('villes.update', ville.id), formData, {
            forceFormData: true, // Explicitly forcing FormData
        });
    };

    // ... (rest of the component - as in your code) ...
}

And here's the update method in my Laravel controller (VilleController.php):

<?php

namespace App\Http\Controllers;

use App\Models\Ville;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Storage;

class VilleController extends Controller
{
    // ... other methods ...

    public function update(Request $request, Ville $ville)
    {
        try {
            Log::info('perform a update action 
发布评论

评论列表(0)

  1. 暂无评论