如何使用Laravel将JSON元素保存为数据库中的记录?
How to save JSON elements as records in the database with Laravel?
我有这些 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();
}
我有这些 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();
}