Count Documents
On this page
You can count the number of documents returned by a query by creating a query builder, using a method such
as Model::where()
or the DB
facade to match documents in a collection, and then calling the count()
method to retrieve the results..
Example
This usage example performs the following actions:
Uses the
Movie
Eloquent model to represent themovies
collection in thesample_mflix
databaseCounts the documents from the
movies
collection that match a query filterPrints the matching document count
The example calls the following methods on the Movie
model:
where()
: Matches documents in which the value of thegenres
field includes"Biography"
.count()
: Counts the number of matching documents. This method returns an integer value.
$count = Movie::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.