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
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseCounts the documents from the
moviescollection 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 thegenresfield 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
moviescollection by calling thetable()method from theDBfacadeCounts the documents from the
moviescollection 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 thegenresfield 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.