填写所有字段后,拉拉维尔发送错误'required'



我正在尝试在 laravel 中使用 axios post 请求提交表单。在这种形式中,我有 3 个字段,名称、年龄和一个名为 image 的文件。

这是表格

<form action="{{route('forms.store')}}" method="post" enctype="multipart/form-data">
@{{name}}
@csrf
<span v-if="errors.name">@{{errors.name[0]}}</span>
<label for="name">Name:</label>
<input type="text" name="name" id="name" v-model="name">
<span v-if="errors.age">@{{errors.age[0]}}</span>
<label for="age">Age:</label>
<input type="text" name="age" id="age" v-model="age">
<label for="image">Image:</label>
<span v-if="errors.image">@{{errors.image[0]}}</span>
<input type="file" name="image" id="image" @change="imageChanged">
<button @click.prevent="submitForm">Submit</button>
</form>

这是我的 vueJs 代码:

const app = new Vue({
el: '#app',
data:{
name:'',
age:'',
image:'',
errors:{}
},
methods:{
imageChanged(e){
app.image = e.target.files[0]
console.log(e.target.files[0]);
},
submitForm(){
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
const fd = new FormData(this.$data);
fd.append('image',this.image);
axios.post('{{route('forms.store')}}',this.fd,config).then((response)=>{
console.log(response.data);
}).catch((error)=>{
//console.log(error.response.data);
this.errors = error.response.data.errors;
})
}
}
});

这是我的控制器

public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'age' => 'required',
]);
if ($request->hasFile('image')) {
$image = $request->file('image');
return $ext = $image->extension();
} else {
return "NOT OK";
}
}

所以在这里我正在验证姓名和年龄。但我的问题是当我填写表格并提交表格时, 它会发回名称和年龄字段是必需的错误。

我哪里做错了以及如何在控制器中接收这些数据。 提前谢谢你。

我相信你的代码在这部分是错误的。 更改:

axios.post('{{route('forms.store')}}',this.fd,config)

自:

axios.post('{{route('forms.store')}}',fd,config)

相关内容