I assume you have a relationship set up?
$users = User::has('connection')->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I have 2 tables User and Connections
In the connection table, I have 3 columns
1 - status
2 - user_id
3 - connection id
I want all users except those who are available in Connections table
I assume you have a relationship set up?
$users = User::has('connection')->get();
@Sinnbeck Thanks for the reply Yes, I have a relationship when I call.
User
public function connection()
{
return $this->hasMany(Connection::class,'connection_with');
}
Connection
public function user()
{
return $this->belongsTo(User::class);
}
Actually, I want suggested users in my tab for example when we open facebook we get the list of suggested users and if we connect with that user then that particular user will not show in our suggested list. so first I need list of all user except those who are not in my connection table I hope sir you understand my point
@tayyabshahzad1 So the connection_id cannot be the logged in user or ?
$users = User::has(['connection' => function($query) {
$query->where('connection_id', '<>', auth()->id());
})->get();
//or
$users = User::whereRelation('connection', 'connection_id', '<>', auth()->id())->get();
@Sinnbeck Sir connection_id is also a login user for example I have 3 user A,B & C if A is login into his account then A we see suggestion for B & C , if A makes a connection with C then only B user will remain in suggested list because C user data in now in connection table
You can use doesntHave or whereDoesntHave
$users = User::whereDoesntHave('connection')->get();
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-absence
@MohamedTammam Thanks
@tayyabshahzad1 If that answers you question, please close the discussion.
@MohamedTammam this is working but the issue is If I marked User A as Connected for B then user C try to login and in listing page user A is not able to find bcz user A is in connection table.
so I want if User B is marked as connected for user A then I log in as user A it will show all users in my listing except B because B is connected for A but if I log in from other users which is C then it will show all users.
for example
users A, B & C
1- if user B is connected to user A
then i log in as user A at that time user B will not show
2-if user i login as user C into my account
then all users will show because we didn't mark any users as connected for user C
If it's working, credit the giver of said working answer and open another thread for a different problem... simple
$users = User::where('id', '!=', auth()->id()) // Don't include current user
->whereDoesntHave('connection', function($q){
$q->where('connection_id', auth()->id()); // Connection with the current user.
})
->get();
Please or to participate in this conversation.