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.

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.

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 the movies collection in the sample_mflix database

  • Inserts a document into the movies collection

  • Prints the newly inserted document

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

  • 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();
{
"title": "Marriage Story",
"year": 2019,
"runtime": 136,
"updated_at": "...",
"created_at": "...",
"_id": "..."
}

This example performs the following actions:

  • Accesses the movies collection by calling the table() method from the DB facade

  • Inserts a document into the movies collection

  • Prints whether the insert operation succeeds

The example calls the insert() method to insert a document that contains the following fields and values:

  • title value of "Marriage Story"

  • year value of 2019

  • runtime value of 136

$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.

Back

Find Multiple Documents

On this page