I want to search for users previous relations but not sure how to make this logic happen.
Logic
- My table has 2 columns
from_idto_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:
whereinput id is from_id and header id is to_idORwhere input id is to_id and header id is from_id` return the result otherwise is null obviously.
Note:
The part that I'm stuck in is and in conditions input id is from_id and header id is to_id OR where input id is to_id and header id is from_id
Code
currently I have half way code which is this:
public function check(Request $request) {
// user id from header request (request sender) e.g `1`
$user = $request->user();
// second user id (not sure where to use it yet) e.g `4`
$request->input('receiverId');
$chat = PrivateChat::where('from_id', $user->id)->orWhere('to_id', $user->id)->first();
}
To make it simple
Basically I want return old chat between the 2 ids regardless of who was sender (from_id) and who was receiver (to_id).
Any idea how to make my logic happen?
Update
this is my full code and it always return false while i do have previous chat between users with id 1 and 4.
public function check(Request $request) {
$user = $request->user();
$chat = PrivateChat::where([['from_id', $user->id],['to_id',$request->input('receiverId')]])
->orWhere([['from_id', $request->input('receiverId')],['to_id',$user->id]])->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.'
]);
}
}