Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

Insert Multiple Documents

On this page

  • Example

You can insert multiple documents into a collection by calling the insert() method on an Eloquent model or a query builder.

To insert multiple documents, call the insert() method and specify the new documents as an array inside the method call. Each array entry contains a single document's field values.

This usage example performs the following actions:

  • Uses the Movie Eloquent model to represent the movies collection in the sample_mflix database

  • Inserts documents into the movies collection

  • Prints whether the insert operation succeeds

The example calls the insert() method to insert documents that contain information about movies released in 2023. If the insert operation is successful, it returns a value of 1. If the operation fails, it throws an exception.

$success = Movie::insert([
[
'title' => 'Anatomy of a Fall',
'release_date' => new UTCDateTime(new DateTimeImmutable('2023-08-23')),
],
[
'title' => 'The Boy and the Heron',
'release_date' => new UTCDateTime(new DateTimeImmutable('2023-12-08')),
],
[
'title' => 'Passages',
'release_date' => new UTCDateTime(new DateTimeImmutable('2023-06-28')),
],
]);
echo 'Insert operation success: ' . ($success ? 'yes' : 'no');
Insert operation success: yes

To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.

Tip

To learn more about insert operations, see the Insert Documents section of the Write Operations guide.

Back

Insert a Document

On this page