Insert Multiple Documents
On this page
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.
Tip
To learn more about insert operations, see the Insert Documents section of the Write Operations guide.
Example
Select from the following Eloquent and Query Builder tabs to view usage examples for the same operation that use each corresponding query syntax:
This example performs the following actions:
Uses the
Movie
Eloquent model to represent themovies
collection in thesample_mflix
databaseInserts documents into the
movies
collectionPrints whether the insert operation succeeds
The example calls the insert()
method to insert documents that represent
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
This example performs the following actions:
Accesses the
movies
collection by calling thetable()
method from theDB
facadeInserts documents into the
movies
collectionPrints whether the insert operation succeeds
The example calls the insert()
method to insert documents that represent
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 = DB::table('movies') ->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.