I have function where I try to search in 2 columns for matched id but in all times it return true even where there is actually no result.
I want to search for users previous relations but not sure how to make this logic happen.
Logic
- My table has 2 columns
from_idandto_id(both will get users ids) - I am sending 2 ids to back-end (one as input, another one in request header)
- I want to say: where input
idisfrom_idand header id isto_id, ORwhere inputidisto_idand headeridisfrom_idreturn the result otherwise is null obviously.
Code
public function check(Request $request) { // always return true!
$user = $request->user();
$userInput = $request->input('receiverId');
$chat = PrivateChat::where(function ($query) use ($user) {
$query->where('from_id', $user->id)->orWhere('to_id', $user->id);
})->orWhere(function ($query) use ($userInput) {
$query->where('from_id', $userInput)->orWhere('to_id', $userInput);
})->first();
$receiver = User::where('id', $request->input('receiverId'))->first();
if($chat) {
return response()->json([
'data' => new PrivateChatResource($chat),
'exist' => true,
'receiver' => new UserResource($receiver),
'message' => 'Chat data retrieved successfully.'
]);
} else {
return response()->json([
'exist' => false,
'receiver' => new UserResource($receiver),
'message' => 'Chat data retrieved successfully.'
]);
}
}
Note: this is follow up of my older question.
Any idea what is the issue?
Update
Based on Giacomo M comment i think this should be the final code
$chat = PrivateChat::where(function ($query) use ($user, $userInput) {
$query
->where('from_id', $user->id)
->where('to_id', $userInput);
})->orWhere(function ($query) use ($user, $userInput) {
$query
->where('from_id', $userInput)
->where('to_id', $user->id);
})->first();
makes sense?