如何使用Vue,Axios和Laravel更新产品记录

时间:2020-06-20 08:38:35

标签: laravel vue.js axios

当我检查数据库中的响应为null时,我的Vue使用axios put方法从ant-design发送了一个表单,我尝试了几次尝试将正确的参数传递失败。传递参数的正确语法是什么。

这是我在Vue中的表格

<a-form :form="formEdit">
<a-input type="text" class="form-control" :value="show1prod.product_name" @input="show1prod.product_name = $event.target.value" />
<a-textarea :value="show1prod.product_description" @input="show1prod.description_name = $event.target.value" :rows="5" />
<button type="button" html-type="submit" @click="update(show1prod.id)" class="btn btn-default">Save</button>
</a-form>

这是axios put配置

import axios from 'axios'
const Api = axios.create({
  baseURL: 'http://localhost:8000/api',
  withCredentials: true
})

Api.defaults.withCredentials = true

export default Api
export default {
    
    update (id,product_name, product_description) {
        return Api.put('/products/update/' + id,product_name, product_description)
    }
    
}

这个脚本我没有包括整个导出默认值,这是里面的内容

data(){
 return{
  formEdit:  {
    product_name: '',
    product_description: ''
  }
 }
},
methods(){
 update (id) {
       let product_name = this.show1prod.product_name;
       let product_description = this.show1prod.product_description;
          Products.update(id, product_name, product_description)
          .then((response) => {
            //this.product_name = response.data
            alert('success')
          })
          .catch((error) => {
            alert(error)
          })
        }
}

这是我的Laravel路线和控制器代码

Route::put('/products/update/{id}', 'ProductsController@update');
public function update(Products $request, $id)
    {
        $id = Products::find($id);
        
        request()->validate([
            'product_name' => 'required',
            'product_description' => 'required'
        ]);
        $id->product_name = $request->product_name;
        $id->product_description = $request->product_description;
        $id->save();
        return response()->json($id);
    }

我想念什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您没有通过put请求发送数据,一个简单的示例如下所示,

<template>
  <form @submit.prevent="submit">
      <input v-model="formEdit.product_name">
      <textarea v-model="formEdit.product_description">
  </form>
</template>

<script>
import axios from 'axios'

export default {
    data() {
        return {
            formEdit: {
                product_name: "",
                product_description: ""
            }
        }
    },

    methods: {
        submit(){
            axios.put('/product/update', this.formEdit)
        }
    },
}
</script>