Docs Menu

Count Documents

On this page

You can count the number of documents returned by a query by using a method such as Model::where() or methods from the DB facade to match documents, and then calling the count() method to retrieve the results.

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

  • 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 and returns the count as an integer

$count = Movie::where('genres', 'Biography')
->count();
echo 'Number of documents: ' . $count;
Number of documents: 1267

This example performs the following actions:

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

  • Counts the documents from the movies collection that match a query filter

  • Prints the matching document count

The example calls the following query builder methods:

  • where(): Matches documents in which the value of the genres field includes "Biography"

  • count(): Counts the number of matching documents and returns the count as an integer

$count = DB::table('movies')
->where('genres', 'Biography')
->count();
echo 'Number of documents: ' . $count;
Number of documents: 1267

To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.

On this page