laravel,vue3,inertiaを活用したCRUD処理でedit.vueの編集後formデータを渡す際、編集内容は記述済みなのにバリデーションエラーが生じる

実現したいこと

laravel,inertia,vue3でCRUD処理を用いた掲示板アプリを作成中です。投稿編集ページで編集内容を送信したところ、編集内容にかかわらずバリデーションエラー文が出てしまい投稿編集内容が反映されません。

発生している問題・分からないこと

vueから画像アップロードをする際にHTTP動詞のPUTリクエストを送ってもlaravelではPOSTとして受け取ってしまってリクエストデータがnullになった結果なのでしょうか?原因と対処法を教えて頂けると嬉しいです。以下にedit.vue、web.php、Postcontroller.phpのupdateメソッドの内容を添付します。

該当のソースコード

edit.vue

1const props = defineProps({ 2 post: { 3 type: Object, 4 required: true, 5 } 6}); 7 8const form = useForm({ 9 title: props.post.title || '', 10 content: props.post.content || '', 11 image: null, 12 _method: 'PUT', 13}); 14 15 16const handleFileChange = (e) => { 17 form.image = e.target.files[0]; 18} 19 20const submit = (post)=>{ 21 console.log(form.data()); 22 form.put(`/posts/${post.id}`,post.id),{ 23 forceFormData:true, 24 onError:()=>{ 25 console.log('error!'); 26 } 27 } 28 29}; 30 31</script> 32 33<template> 34 <Head title="投稿編集" /> 35 <div> 36 <h1>投稿編集</h1> 37 <!-- 画像データの時はformにenctype必須 --> 38 <form @submit.prevent="submit(post)" enctype="multipart/form-data"> 39 <div> 40 <label for="title">タイトル</label> 41 <input v-model="form.title" id="title" type="text" /> 42 <div v-if="form.errors.title" class="text-red-600">{{ form.errors.title }}</div> 43 </div> 44 <div> 45 <label for="content">レシピ詳細</label> 46 <textarea v-model="form.content" id="content"></textarea> 47 <div v-if="form.errors.content" class="text-red-600">{{ form.errors.content }}</div> 48 </div> 49 <div> 50 <label for="image">画像アップロード</label> 51 <input @change="handleFileChange" type="file" id="image" /> 52 </div> 53 <button type="submit">送信</button> 54 </form> 55 <div v-if="post.image_path"> 56 <img class="h-auto max-w-14 rounded-lg" :src="post.image_path" alt="Current Image"/> 57 </div> 58 </div> 59</template> 60

web.php

1Route::resource('posts', PostController::class);

postcontroller.php

1public function update(PutRequest $request, string $id) 2 { 3 $post = Post::findOrFail($id); 4 $validated = $request->validated(); 5 6 // 画像がアップロードされた場合の処理 7 if ($request->hasFile('image')) { 8 // 既存の画像を削除 9 if ($post->image_path) { 10 try { 11 Storage::disk('s3')->delete($post->image_path); 12 // 新しい画像をアップロード 13 $imagePath = $request->file('image')->store($this->diskImageFolder, 's3'); 14 $validated['image_path'] = Storage::disk('s3')->url($imagePath); 15 } catch (\Exception $e) { 16 return back()->withErrors(['image' => '画像のアップロードに失敗しました: ' . $e->getMessage()]); 17 } 18 } 19 } 20 // 投稿を更新 21 $post->update($validated); 22 23 return redirect()->route('posts.index'); 24 }

試したこと・調べたこと

上記の詳細・結果

chatGPTやstackoverflowにも質問しましたが解決には至っていません。

補足

特になし

コメントを投稿

0 コメント