2

Is it possible to insert several eloquent models in one query?

Let's say I have eloquent model Page and I want to insert array of pages or collection of pages in one query

$page1 = new Page();
$page2 = new Page();
$pages = [
  $page1,
  $page2,
];
or
$pages = Collection([$page1, $page2]);

I want something like

$pages->save();

But it warns that "Method save does not exist".

I saw this, but there they insert array of arrays and I want to insert array of eloquent models.

Community
  • 1
  • 1
melihovv
  • 1,055
  • 1
  • 10
  • 15

1 Answers1

0

You could try the saveMany() option.

This example might work for you:

DB::table('pages')->saveMany($pages);

And if you are working with relationships you can even use a "cleaner" way (just showing you example of ways to use this function):

$book = App\Book::find(1);

$book->pages()->saveMany([
    new App\Page(['title' => 'A new page.']),
    new App\Page(['title' => 'Another page.']),
]);
Dees Oomens
  • 4,554
  • 3
  • 29
  • 61