【问题标题】:After Filling all Fields laravel sending 'required' error填写所有字段后,laravel 发送“必需”错误
【发布时间】:2018-11-21 16:14:24
【问题描述】:

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

这是表格

<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";
    }
}

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

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

【问题讨论】:

  • 打印您的请求数据并检查。
  • 看来你在你的 vue JS 中传递了姓名和年龄空白
  • @RakeshSojitra 那么问题出在哪里……在我的 vue 开发者工具中,名称和年龄是有价值的……

标签: javascript php laravel vue.js axios


【解决方案1】:

我相信您的代码在这部分有误。变化:

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

到:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-26
    • 2013-11-14
    • 2019-06-03
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2016-04-19
    • 2016-07-04
    相关资源
    最近更新 更多