The count()
function is a very useful function in Laravel. It has many advantages like counting the number of rows for a database table or counting items in an array collection count()
is one of the aggregate functions like max()
and min()
offered by Laravel Eloquent to perform operations. Consider the code snippet below on how you can use the count()
function in Laravel.
Count Array Elements with count function
Here’s how you can use the count()
function in Laravel.
$data = collect([1, 2, 3, 5, 2, 8, 1, 5, 4);
$total = $data->count();
echo "Total Collection Items: " . $total;
// outputs 9
The $total
variable here counts the number of items in the array collect using the count()
function.
Count Database Rows with the count function
Consider the code snippet below where you can add the User model, that holds database for user’s details.
use App\Models\User; // Assuming you have a User model
$count = User::where('age', '>', 18)->count();
You can then simply pass the count() method as shown above to any database query. Suppose, to find the number of users above the age of 18, you can pass the count function as shown above.