Laravel Eloquent model has a way for you to return the total number of rows of a related model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\Product;
class User extends Authenticatable
{
.....
public function products() {
return $this->hasMany(Product::class);
}
}
Now you can use it like this.
$users = User::withCount('products_count')->get();
foreach ($users as $user) {
echo $user->products_count;
}

