|
| 1 | +.. _laravel-find-one-usage: |
| 2 | + |
| 3 | +=============== |
| 4 | +Find a Document |
| 5 | +=============== |
| 6 | + |
| 7 | +You can retrieve a single document from a collection by calling the ``where()`` and |
| 8 | +``first()`` methods on an Eloquent model or a query builder. |
| 9 | + |
| 10 | +Pass a query filter to the ``where()`` method and then call the ``first()`` method to |
| 11 | +return one document in the collection that matches the filter. If multiple documents match |
| 12 | +the query filter, ``first()`` returns the first matching document according to the documents' |
| 13 | +:term:`natural order` in the database or according to the sort order that you can specify |
| 14 | +by using the ``orderBy()`` method. |
| 15 | + |
| 16 | +Example |
| 17 | +------- |
| 18 | + |
| 19 | +This usage example performs the following actions: |
| 20 | + |
| 21 | +- Uses the ``Movie`` Eloquent model to represent the ``movies`` collection in the |
| 22 | + ``sample_mflix`` database. |
| 23 | +- Retrieves a document from the ``movies`` collection that matches a query filter. |
| 24 | + |
| 25 | +The example calls the following methods on the ``Movie`` model: |
| 26 | + |
| 27 | +- ``where()``: matches documents in which the value of the ``directors`` field includes ``'Rob Reiner'``. |
| 28 | +- ``orderBy()``: sorts matched documents by their ascending ``_id`` values. |
| 29 | +- ``first()``: retrieves only the first matching document. |
| 30 | + |
| 31 | +.. io-code-block:: |
| 32 | + |
| 33 | + .. input:: ../includes/usage-examples/FindOneTest.php |
| 34 | + :start-after: begin-find-one |
| 35 | + :end-before: end-find-one |
| 36 | + :language: php |
| 37 | + :dedent: |
| 38 | + |
| 39 | + .. output:: |
| 40 | + :language: console |
| 41 | + :visible: false |
| 42 | + |
| 43 | + // Result is truncated |
| 44 | + |
| 45 | + { |
| 46 | + "_id": "573a1398f29313caabce94a3", |
| 47 | + "plot": "Spinal Tap, one of England's loudest bands, is chronicled by film director |
| 48 | + Marty DeBergi on what proves to be a fateful tour.", |
| 49 | + "genres": [ |
| 50 | + "Comedy", |
| 51 | + "Music" |
| 52 | + ], |
| 53 | + "runtime": 82, |
| 54 | + "metacritic": 85, |
| 55 | + "rated": "R", |
| 56 | + "cast": [ |
| 57 | + "Rob Reiner", |
| 58 | + "Kimberly Stringer", |
| 59 | + "Chazz Dominguez", |
| 60 | + "Shari Hall" |
| 61 | + ], |
| 62 | + "poster": "https://m.media-amazon.com/images/M/MV5BMTQ2MTIzMzg5Nl5BMl5BanBnXkFtZTgwOTc5NDI1MDE@._V1_SY1000_SX677_AL_.jpg", |
| 63 | + "title": "This Is Spinal Tap", |
| 64 | + ... |
| 65 | + } |
| 66 | + |
| 67 | + |
| 68 | +For instructions on editing your Laravel application to run the usage example, see the |
| 69 | +:ref:`Usage Example landing page <laravel-usage-examples>`. |
| 70 | + |
| 71 | +.. tip:: |
| 72 | + |
| 73 | + To learn more about retrieving documents with {+odm-short+}, see the |
| 74 | + :ref:`laravel-fundamentals-retrieve` guide |
0 commit comments