Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RimiCsani's avatar

Save array of objects in one mysql query

Hi!

How can I insert in mysql the following array of objects in one query using eloquent or query builder?

[ { "name": "John", "surname": "Doe" }, { "name": "Jane", "surname": "Doe" }, { "name": "John", "surname": "Dean" }

]

Thank you!

0 likes
14 replies
RimiCsani's avatar

Hi!

Thanks for your response! I tried the saveMany and createMany methods but they give me an error: Call to undefined method App\Models\MyModel::saveMany()

I am trying to save in a mysql table an array of objects, like the one I posted in the question, returned by an API call. Do you know an efficient way to do it in Laravel?

Thanks for your help!

RimiCsani's avatar

Hi!

I don't have (and I don't need) relationships for that table. It has just to be filled with data that come from an API call, nothing else.

Thanks!

RimiCsani's avatar

@lemmon In many records. I was wondering if there is a Laravel helper method to insert the entire array, in multiple records, in one query

Thanks!

RimiCsani's avatar

@michaloravec thanks!

I guess I have to loop through each of them or do you have a suggestion about how to convert those objects efficiently?

MichalOravec's avatar
$data = collect($data)->map(function ($item) {
   return (array) $item;   
})->toArray();
1 like
RimiCsani's avatar

Hi @michaloravec! I tried your method but it doesn't convert. The objects inside the array all have the same structure as I described in the question.

Thanks a lot!

Please or to participate in this conversation.