Laravel Eloquent Count Rows with examples

December 1, 2021
Laravel
Laravel Eloquent Count Rows with examples

In this post, you will learn how to get row count in laravel eloquent. This is the common thing to do to get the total rows in the table.

By the end of the article, you will be able to perform laravel eloquent count rows queries.

Let’s get started!

Syntax of getting count in laravel eloquent

ModelName::count();

Example 1:

Let’s say we want to how many users we have in the Users table. In the controller, you will write the following code

$count=User::count();
echo $count;

Example 2 with DB class:

In this example, we will get the total users using the DB class:

$count=DB::table('users')->count();
echo $count;

Example 3 with where condition:

Let me show you another example with the where condition. We will get total no. users that are admin from the Users table

$count=User::where('is_admin',1)->count();
echo $count;

Conclusion:

Hope you have learned today how to count number of rows in laravel eloquent.

Let me know if you have any questions in the comments below.

See you soon in another tutorial!

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon