Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ncarreno's avatar

Get number of rows after group by

Hi everyone,

I have a question I can't sort out. I have a table where I register every time a user logs in my website. In this table I record user id, ip, date in a table a have called "customer_logs". I have my Model CustomerLog related with the model Customer:

class CustomerLog extends Model
{
    protected $table = 'customers_log';

    protected $fillable=[
        'id',
        'customer_id',
        'ip',
        'created_at',
      
    ];

    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }

This is an example of the records in this table:

user_1 - 192.0.0.1 - 2021-11-23
user_1 - 192.0.0.2 - 2021-11-23
user_1 - 192.0.0.3 - 2021-11-23
user_2 - 192.1.1.1 - 2021-11-23

I want to get a list of the customers (user_1 and user_2 in this example) and I want to show how many IPs the user has used and how many records has the user un te table. This is an example:

user_1_name - 3ips - 3 rows
user_2_name - 1ips - 1 rows

I have this elquence sentence, I group by customer but after that, what would be the best way to get the data I want to show?

$users=CustomerLog::whereDate('created_at', Carbon::today())->groupBy('customer_id')->get();

Thanks for your answers

0 likes
6 replies
bugsysha's avatar

Following should work:

@foreach ($users as $user)
  {{ $user->pluck('ip')->unique()->count() }}
@endforeach
ncarreno's avatar

It doesn't work the way I want. Your code shows the number of ips of all records from each customer but I want to show only the number of ips the user have used today.

$users=CustomerLog::whereDate('created_at', Carbon::today())->groupBy('customer_id')->get();
bugsysha's avatar

@ncarreno my code doesn't do anything regarding what is fetched from the database. That is done by your query. If your query is wrong then you need to scope it to today. You were asking how to show it, not how to fetch it from the DB.

ncarreno's avatar

@bugsysha Sorry I didn't explain it well. What I meant was how fetch the number of different ips from each customer after use the groupBy or if there is another way to get this data.

bugsysha's avatar

@ncarreno grab all and do what you need in PHP.

$users=CustomerLog::whereDate('created_at', Carbon::today())->get()->groupBy('customer_id');

Please or to participate in this conversation.