如何使用Laravel将JSON元素保存为数据库中的记录?



我有这些JSON数据,我发送失眠:

[
{ "name": "Michel", "phone": "+213 93 783 28 73", "users_id": "1"},
{ "name": "Annie", "phone": "+213 93 783 28 72", "users_id": "1"},
{ "name": "Rory", "phone": "+16505551212", "users_id": "1"},
{ "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();
}

相关内容

  • 没有找到相关文章

最新更新