The `count()` method in Laravel 12 counts the number of records in a database table.
Basic `count()` Example
<?php use App\Models\User; $totalUsers = User::count(); echo "Total Users: " . $totalUsers; ?>
Counts all users in the `users` table.
Count with `where()` Condition
<?php $activeUsers = User::where('status', 'active')->count(); echo "Active Users: " . $activeUsers; ?>
Counts only **users with status = ‘active’.
Count with `whereBetween()`
<?php use Carbon\Carbon; $startDate = Carbon::now()->subDays(30); $endDate = Carbon::now(); $monthlyUsers = User::whereBetween('created_at', [$startDate, $endDate])->count(); echo "Users registered in the last 30 days: " . $monthlyUsers; ?>
Counts users registered in the last 30 days.
Count with `groupBy()` (Count by Category)
<?php use App\Models\Product; $categoryCounts = Product::select('category', DB::raw('count(*) as total')) ->groupBy('category') ->get(); foreach ($categoryCounts as $category) { echo "Category: " . $category->category . " - Total: " . $category->total . "<br>"; } ?>
Counts products in each category.
Count in Relationship (Example: Count User Posts)
<?php $user = User::withCount('posts')->find(1); echo "User has " . $user->posts_count . " posts."; ?>
Retrieves user with the total count of their posts.
Using Query Builder
<?php use Illuminate\Support\Facades\DB; $totalOrders = DB::table('orders')->count(); echo "Total Orders: " . $totalOrders; ?>