The current query, a user will have to have both doctors and friends.
If its either, then use orWhereHas for the second search
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am trying to search through two tables in one query, as a User, who hasMany friends (User.php), and doctors (Doctor.php).
Unfortunately the following logic is not working. I get a blank collection event though there must be at least a friend within, as I tried the solo-query for the friends before.
$month is a simple input request to check on the date within the friends, and doctors table.
$friends = Auth::user()->friends(); (User.php)
$doctors = Auth::user()->doctors(); (Doctor.php)
$result = Auth::user()->whereHas('doctors', function($query) use ($month) {
$query->whereMonth('date', '=', $month);
})->whereHas('friends', function($query) use ($month) {
$query->whereMonth('date', '=', $month);
})->paginate(10);
Any suggestions?
You can obviously merge the collections, but I don't see how you would ever be able to paginate the results.
$friends = Auth::user()
->friends()
->where('accepted',1)
->whereMonth('date', '=', $request->month)
->get();
$result = $friends->merge(
Auth::user()
->doctors()
->where('accepted',1)
->whereMonth('date', '=', $request->month)
->get()
)
->sortBy('created_at','desc');
return view ('search.result', compact('result'));
For pagination, I think you would need to use joins to create one resultset.
Please or to participate in this conversation.