我正尝试将一些数据作为“报价”数组发布到我的Laravel后端:
这就是邮递员的样子和工作原理: 键:提供[title] ,提供[description] ,提供[author_user_id]
现在使用axios,我已经尝试过类似的操作:
offer: {
title: this.input.title,
description: this.input.description,
author_user_id: id,
}
也尝试过: [key => val] ,例如 offer.title:value ,但也失败。
它看起来如何?
编辑:
this.axios.post('http://api.wip/api/offer/store', {
offer: {
title: this.input.title,
description: this.input.description,
author_user_id: id,
},
category: 2
}, {
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'application/json'
}
})
.then(function () {
})
.catch(function () {
});
在我的控制台中,我可以看到它的发送方式为:
{"offer":{"title":"asd","description":"asd","author_user_id":"2"},"category":2}:
我从服务器收到500错误,并收到Laravel的回应,它期望数据为数组。
"message": "Argument 1 passed to Illuminate\\Database\\Eloquent\\Builder::create() must be of the type array, null given, called in D:\\wamp64\\www\\apitest\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Traits\\ForwardsCalls.php on line 23",
正如我所说的,它可以与邮递员一起使用,但是不能从axios上使它起作用
Laravel控制器:
public function store(Request $request) {
$offer = Offer::create($request->input('offer'));
$offer->category()->sync($request->input('category'));
$offer->save();
return response()->json($offer);
}
答案 0 :(得分:0)
Boussadjra Brahim是对的,问题出在后端,但这是由于从前端发送空值引起的,因此我们必须看一下前端。
第一件事是使用{}表示您正在创建对象,[]是数组,而laravel create方法仅接受数组
输入本身就是一个数组,因为您正在使用(dot)访问键,所以为什么不只为整个数组设置offer,然后在后端将它们分开呢?像这样
axios.post('http://api.wip/api/offer/store', {
offer:this.input,
author_user_id: id,
category: 2
},
在您的后端,您可以像这样访问它们:
$title = $request->offer['title'];
最后一件事,当您使用create方法时,键名必须与数据库中的列名相同,否则将引发错误! 希望对您有帮助