问题描述
我有这些用 Insomnia 发送的 JSON 数据:
[
{ "name": "Michel","phone": "+213 93 783 28 73","users_id": "1"},{ "name": "Annie","phone": "+213 93 783 28 72",{ "name": "Rory","phone": "+16505551212",{ "name": "CESI","phone": "+213 58 357 31 78","users_id": "1"}
]
我想使用 Laravel 在我的数据库中保存为记录,这是我的代码,我不明白该怎么做:
public function store(Request $request){
foreach ($request as $requests) {
$contact = new Contact();
$contact->name = $requests['name'];
$contact->phone = $requests['phone'];
$contact->users_id = $requests['users_id'];
$contact->save();
}
}
我收到此错误:
Cannot use object of type Symfony\\Component\\HttpFoundation\\ParameterBag as array
解决方法
您当前正在迭代请求对象,何时应该使用 $request->json()->all()
迭代其数据:
foreach ($request->json()->all() as $record) {
$contact = new Contact();
$contact->name = $record['name'];
$contact->phone = $record['phone'];
$contact->users_id = $record['users_id'];
$contact->save();
}