Insert a Document
On this page
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
Movie
Eloquent model to represent themovies
collection in thesample_mflix
databaseInserts a document into the
movies
collectionPrints 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 of2019
runtime
value 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
movies
collection by calling thetable()
method from theDB
facadeInserts a document into the
movies
collectionPrints 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 of2019
runtime
value 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.