|
| 1 | +.. _laravel-update-one-usage: |
| 2 | + |
| 3 | +================= |
| 4 | +Update a Document |
| 5 | +================= |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: update one, modify, code example |
| 13 | + |
| 14 | +.. contents:: On this page |
| 15 | + :local: |
| 16 | + :backlinks: none |
| 17 | + :depth: 1 |
| 18 | + :class: singlecol |
| 19 | + |
| 20 | +You can update a document in a collection by retrieving a single document and calling |
| 21 | +the ``update()`` method on an Eloquent model or a query builder. |
| 22 | + |
| 23 | +Pass a query filter to the ``where()`` method, sort the matching documents, and call the |
| 24 | +``first()`` method to retrieve only the first document. Then, update this matching document |
| 25 | +by passing your intended document changes to the ``update()`` method. |
| 26 | + |
| 27 | +Example |
| 28 | +------- |
| 29 | + |
| 30 | +This usage example performs the following actions: |
| 31 | + |
| 32 | +- Uses the ``Movie`` Eloquent model to represent the ``movies`` collection in the |
| 33 | + ``sample_mflix`` database. |
| 34 | +- Updates a document from the ``movies`` collection that matches a query filter. |
| 35 | + |
| 36 | +The example calls the following methods on the ``Movie`` model: |
| 37 | + |
| 38 | +- ``where()``: matches documents in which the value of the ``title`` field is ``'Carol'``. |
| 39 | +- ``orderBy()``: sorts matched documents by their ascending ``_id`` values. |
| 40 | +- ``first()``: retrieves only the first matching document. |
| 41 | +- ``update()``: updates the value of the ``imdb.rating`` nested field to from ``6.9`` to |
| 42 | + ``7.3``. This method also updates the ``imdb.votes`` nested field from ``493`` to ``142000``. |
| 43 | + |
| 44 | +.. io-code-block:: |
| 45 | + :copyable: true |
| 46 | + |
| 47 | + .. input:: ../includes/usage-examples/UpdateOneTest.php |
| 48 | + :start-after: begin-update-one |
| 49 | + :end-before: end-update-one |
| 50 | + :language: php |
| 51 | + :dedent: |
| 52 | + |
| 53 | + .. output:: |
| 54 | + :language: console |
| 55 | + :visible: false |
| 56 | + |
| 57 | + Updated documents: 1 |
| 58 | + |
| 59 | +For instructions on editing your Laravel application to run the usage example, see the |
| 60 | +:ref:`Usage Example landing page <laravel-usage-examples>`. |
| 61 | + |
| 62 | +.. tip:: |
| 63 | + |
| 64 | + To learn more about updating data with {+odm-short+}, see the `Updates |
| 65 | + <https://laravel.com/docs/{+laravel-docs-version+}/eloquent#updates>`__ section of the |
| 66 | + Laravel documentation. |
| 67 | + |
0 commit comments