简体   繁体   中英

How to save JSON elements as records in the database with Laravel?

I have these JSON data I send with Insomnia:

[
    { "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"}
]

That I want to be saved as records in my database using Laravel, here's my code I didn't understand how to do it sincerely:

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();
 }
}

I got this error: Cannot use object of type Symfony\\Component\\HttpFoundation\\ParameterBag as array

You are currently iterating over the Request Object, when you should iterate over its data with $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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM