diff --git a/docs/includes/usage-examples/CountTest.php b/docs/includes/usage-examples/CountTest.php new file mode 100644 index 000000000..ecf53db47 --- /dev/null +++ b/docs/includes/usage-examples/CountTest.php @@ -0,0 +1,42 @@ + 'Young Mr. Lincoln', + 'genres' => ['Biography', 'Drama'], + ], + [ + 'title' => 'Million Dollar Mermaid', + 'genres' => ['Biography', 'Drama', 'Musical'], + ], + ]); + + // begin-count + $count = Movie::where('genres', 'Biography') + ->count(); + + echo 'Number of documents: ' . $count; + // end-count + + $this->assertEquals(2, $count); + $this->expectOutputString('Number of documents: 2'); + } +} diff --git a/docs/usage-examples.txt b/docs/usage-examples.txt index 24eae454f..a4015031a 100644 --- a/docs/usage-examples.txt +++ b/docs/usage-examples.txt @@ -75,3 +75,4 @@ calls the controller function and returns the result to a web interface. /usage-examples/updateOne /usage-examples/deleteOne /usage-examples/deleteMany + /usage-examples/count diff --git a/docs/usage-examples/count.txt b/docs/usage-examples/count.txt new file mode 100644 index 000000000..dc3720fc0 --- /dev/null +++ b/docs/usage-examples/count.txt @@ -0,0 +1,57 @@ +.. _laravel-count-usage: + +=============== +Count Documents +=============== + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: total, code example + +.. contents:: On this page + :local: + :backlinks: none + :depth: 1 + :class: singlecol + +You can count the number of documents returned by a query by calling the ``where()`` and +``count()`` methods on a collection of models or a query builder. + +To return the number of documents that match a filter, pass the query filter to the ``where()`` +method and call the ``count()`` method. + +Example +------- + +This usage example performs the following actions: + +- Uses the ``Movie`` Eloquent model to represent the ``movies`` collection in the + ``sample_mflix`` database +- Counts the documents from the ``movies`` collection that match a query filter +- Prints the matching document count + +The example calls the following methods on the ``Movie`` model: + +- ``where()``: Matches documents in which the value of the ``genres`` field includes ``"Biography"``. +- ``count()``: Counts the number of matching documents. This method returns an integer value. + +.. io-code-block:: + + .. input:: ../includes/usage-examples/CountTest.php + :start-after: begin-count + :end-before: end-count + :language: php + :dedent: + + .. output:: + :language: console + :visible: false + + Matching documents: 1267 + + +To learn how to edit your Laravel application to run the usage example, see the +:ref:`Usage Examples landing page `.