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.
Example
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 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 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 thetable()
method from theDB
facadeCounts the documents from the
movies
collection that match a query filterPrints the matching document count
The example calls the following query builder methods:
where()
: Matches documents in which the value of thegenres
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.