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

LorienDarenya's avatar

hasMany relationship only returning one result

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?

0 likes
6 replies
tykus's avatar

The hasMany relationship should be:

$this->hasMany(User::class, 'user_id');
LorienDarenya's avatar

Doing it that way returns an error because the relationship is looking for user_id on the users table, which does not have that column.

tykus's avatar

Wait... an IpLog hasMany User; how does that work? A hasMany relation would require an ip_log_id on the users table, but you have a user_id field on the ip_logs table - this would mean a belongsTo relation:

// IpLog.php

public function observer() {
    return $this->belongsTo(User::class, 'user_id');
}
LorienDarenya's avatar

Darn, you're right. I knew it was something obvious. I still need to return alll the users on that IP, though.

tykus's avatar
tykus
Best Answer
Level 104

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.

LorienDarenya's avatar

Thank you so much for setting me on the right path. I'm going to go reread the docs on relations now. slinks away

1 like

Please or to participate in this conversation.