Search code examples
arraysjsonlaravelforeachmultiple-records

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


Solution

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