4

I have multidimensional array and I want to insert all the data in one query with my model, I know I can do it with DB query builder class, like

 DB::table('table')->insert([ 
     ['name' => 'foo'],
     ['name' => 'bar'],
     ['name' => 'baz']
 ]);

but how can I do it with model? Model::create() doesn't insert multiple records, also I don't want to insert items with loop. is it possible to do this with eloquent?

devnull Ψ
  • 3,779
  • 7
  • 26
  • 43

1 Answers1

9

You can do this with model:

Model::insert([ 
   ['name' => 'foo'],
   ['name' => 'bar'],
   ['name' => 'baz']
]);

But here insert is the same QB method.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Thanks. For anyone else coming here, make sure you use a multi-dimensional array of arrays. I was a dummy and trying to just do `Model::insert(array(), array())` instead of `Model::insert(array(array(),array()));`... just one of those moments... – Casper Wilkes Jun 01 '18 at 03:25
  • 1
    @daisura99 You have to fill those manually since it's using the query builder and not Eloquent. So each line you're inserting needs to have something like: `'created_at' => Carbon::now(), 'updated_at' => Carbon::now(),` – Jamie T Apr 17 '19 at 19:14
  • but it will fail if one of the column didn't exist in db, while `create` will "filter" it so it won't throw error column not found. how to prevent this? – Fahmi Jan 26 '22 at 17:56