How to Use Count in Eloquent: Simple Laravel Query Examples
In Laravel Eloquent, use the
count() method to get the number of records matching a query. You can call Model::count() to count all records or add conditions before count() to count filtered results.Syntax
The count() method returns the total number of records for a query. You can use it directly on a model or after applying query conditions.
Model::count(): Counts all records in the table.Model::where('column', 'value')->count(): Counts records matching the condition.
php
use App\Models\User; // Count all users $totalUsers = User::count(); // Count users with active status $activeUsers = User::where('status', 'active')->count();
Example
This example shows how to count all users and how to count users with a specific condition using Eloquent's count() method.
php
<?php use App\Models\User; // Count all users $totalUsers = User::count(); echo "Total users: " . $totalUsers . "\n"; // Count users where status is 'active' $activeUsers = User::where('status', 'active')->count(); echo "Active users: " . $activeUsers . "\n";
Output
Total users: 50
Active users: 30
Common Pitfalls
One common mistake is calling count() on a collection instead of the query builder, which loads all records into memory and then counts them, causing performance issues.
Use count() directly on the query builder to let the database count records efficiently.
php
<?php use App\Models\User; // Inefficient: loads all users then counts $users = User::all(); $count = $users->count(); // Avoid this for large datasets // Efficient: counts in database $count = User::count();
Quick Reference
| Usage | Description |
|---|---|
| Model::count() | Count all records in the model's table |
| Model::where(...)->count() | Count records matching conditions |
| Collection->count() | Count items in a loaded collection (less efficient for large data) |
Key Takeaways
Use
count() on the query builder to count records efficiently in the database.Add
where conditions before count() to count filtered results.Avoid calling
count() on collections loaded with all() to prevent performance issues.The
count() method returns an integer representing the number of matching records.