The hasMany relationship should be:
$this->hasMany(User::class, 'user_id');
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
This is one of those moments where I have a feeling I'm missing something very obvious, but here we go.
I'm logging user IPs in the database. My table looks like:
ip_logs: id | user_id | ip | city | state | country | created_at | updated_at
Logging IPs through a middleware works great. Now, I'm trying to return a list of users on the same IP, I have the following relationship on my IPLog model:
public function observers() {
return $this->hasMany(User::class, 'id', 'user_id');
}
And finally, I have this in my controller:
protected function getIPLogs() {
$count = IPLog::groupBy('ip')->havingRaw('count(*) >= 3')->count();
$ips = IPLog::with('observers')->groupBy('ip')->havingRaw('count(*) >= 3')->get();
return view('home.ip-logs', compact('count', 'ips'));
}
Now, I expect observers to return the three users on one ip that I see in the database. But it is only returning the first user. Thoughts?
Well, that's a different issue, you will have a hasMany relation on the User model:
// User.php
public function ip_logs()
{
return $this->hasMany(IpLog::class');
}
Then you will scope a user query to the given ip address ($ip):
$users = User::whereHas('ip_logs', function ($query) use ($ip) {
$query->where('ip', $ip);
})->get();
Note that this will return all users who have ever logged that IP address; you can further constraint the whereHas query if required.
Please or to participate in this conversation.