You can insert a document into a collection by calling the create() method on
an Eloquent model or query builder.
To insert a document, pass the data you need to insert as a document containing
the fields and values to the create() method.
Tip
You can also use the save() or insert() methods to insert a
document into a collection. 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
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseInserts a document into the
moviescollectionPrints the newly inserted document
The example calls the create() method to insert a document
that contains the following fields and values:
titlevalue of"Marriage Story"yearvalue of2019runtimevalue of136
$movie = Movie::create([ 'title' => 'Marriage Story', 'year' => 2019, 'runtime' => 136, ]); echo $movie->toJson();
{ "title": "Marriage Story", "year": 2019, "runtime": 136, "updated_at": "...", "created_at": "...", "_id": "..." }
This example performs the following actions:
Accesses the
moviescollection by calling thetable()method from theDBfacadeInserts a document into the
moviescollectionPrints whether the insert operation succeeds
The example calls the insert() method to insert a document
that contains the following fields and values:
titlevalue of"Marriage Story"yearvalue of2019runtimevalue of136
$success = DB::table('movies') ->insert([ 'title' => 'Marriage Story', 'year' => 2019, 'runtime' => 136, ]); 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.