Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

Insert a Document

On this page

  • Example

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.

This usage example performs the following actions:

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

  • Inserts a document into the movies collection

The example calls the create() method to insert a document that contains the following information:

  • title value of "Marriage Story"

  • year value of 2019

  • runtime value of 136

$movie = Movie::create([
'title' => 'Marriage Story',
'year' => 2019,
'runtime' => 136,
]);
echo $movie->toJson();

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

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.

Back

Find Multiple Documents

Next

Insert Multiple Documents

On this page