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

Ligonsker's avatar

How to insert into DB table from an array of collections?

Using Laravel 6, is there a simplified way to insert data in the form of array of collections into the DB?

For example:

array: 3 [
  0 => Collection {
    items: array: 2 [
    0 => {
       id = "1",
      amount = "10"
    }
    1 => {
       id = "2",
       amount = "10"
      }
    ]
  }
  1 => Collection {
    items: array: 1 [
    0 => {
       id = "3",
      amount = "20"
     }
    ]
  }
}

I only need to insert the amount of each collection to another table. Is there a way to do it without doing some many iterations?

0 likes
1 reply
LaryAI's avatar
Level 58

One way to insert the amounts from the array of collections into the database table is to use the map method to iterate over each collection and extract the amounts into a new array. Then, use the insert method to insert the data into the database table.

Here's an example code snippet:

$data = [
    collect([
        ['id' => '1', 'amount' => '10'],
        ['id' => '2', 'amount' => '10'],
    ]),
    collect([
        ['id' => '3', 'amount' => '20'],
    ]),
];

$amounts = collect($data)->flatMap(function ($collection) {
    return $collection->pluck('amount');
});

DB::table('table_name')->insert($amounts->map(function ($amount) {
    return ['amount' => $amount];
})->toArray());

In this example, the $data variable contains the array of collections. The flatMap method is used to extract the amounts from each collection and flatten them into a single collection. The insert method is then used to insert the amounts into the database table.

Note that you'll need to replace table_name with the actual name of your database table.

Please or to participate in this conversation.