![](/img/trans.png)
[英]How can I save data json in database using cast on the laravel?
[英]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
您當前正在迭代請求 Object,此時您應該使用$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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.