使用Axios请求将数据添加到数据库会产生内部服务器错误

时间:2020-02-09 23:17:34

标签: database vue.js axios

我正在使用Vue JS(更具体地说是Vuetify库)创建表单,当单击“添加”按钮时,我试图将其添加,以便将用户输入添加到数据库中。

数据库有3列:id,type_id,value。我想将用户输入链接到值列。

请注意,allDesserts是一个数组,用于存储数据库中的所有项目。这就是我要添加的内容。

我该如何实现?

我的表单中的组件:

    <v-combobox
        :items="allDesserts.map(a => a.value)"
        label="Project Type"
        :search-input.sync="search"
    >
        <template v-slot:no-data> 
            <v-text-field
            label="Add new dessert"
            v-model="search"
            >
            </v-text-field>
                <v-btn 
                @click="enterKey"
                >Add</v-btn>
        </template>
    </v-combobox>

Axios请求/方法:

        enterKey () {
            axios.post('/api/desserts', {
                value: 'key'
            })
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error.response);
                });
        }

我的控制器:

public function storeDessert(Request $request)
{
    $dropdownType = new DropdownType();
    $dropdownType->attribute_id = $request->input(rand(1, 10000));
    $dropdownType->value = $request->input('value');
    $dropdownType->save();
}

我遇到以下错误:

"Illegal string offset 'id'"

1 个答案:

答案 0 :(得分:0)

我认为您的错误就在这行上。

$dropdownType->attribute_id = $request->input(rand(1, 10000));

假设rand(1, 10000)会为您提供100的值,现在您已将此100用作访问请求中不可用的值的密钥。

尝试查看您的有效载荷。您只是在传递包含key value only,即这个数据的数据。

{value: 'key'}

现在这行将起作用,因为它在您的有效负载中可用。

$dropdownType->value = $request->input('value');

但不是这个。

$dropdownType->attribute_id = $request->input(rand(1, 10000));