Save complex object outside foreach

i am trying to store a complex object in database. There are a lot of relationships like one-to-one and one-to-many. Everything works fine but at the moment i am doing the saving inside the foreach loop, which is not correct.

foreach($list as $item){

$objA = new ObjA();
$objA->id = $item['id'];

$objB = new ObjB();
$objB->name = $item['key']['name'];


foreach ($item['data']['products'] as $product) {
    $product = new Product();
    $product->name = $product['name'];


This is the code atm, but i need to execute the query outside the foreach.
How can i achieve this?
products and extra methods are something like that :

    public function extra(){
        return $this->hasOne(ObjB::class);

Source: Laravel

Leave a Reply