I'm trying to build an Eloquent query using an array of email addresses and an array of phone numbers that returns all users that match either one of the phone numbers or one of the email addresses. Here are the methods I've attempted:
Passing a function to where
:
public function findFromContacts($emailAddresses = array(), $phoneNumbers = array()) {
return AppUser::where(function($query) use($emailAddresses, $phoneNumbers) {
foreach($emailAddresses as $emailAddress) {
$query->orWhere('email', $emailAddress);
}
foreach($phoneNumbers as $phoneNumber) {
$query->orWhere('phone', $phoneNumber);
}
})->get();
}
Appending whereOr
clauses with array_reduce
:
public function findFromContacts($emailAddresses = array(), $phoneNumbers = array()) {
$query = AppUser::query();
$queryWithEmailAddresses = array_reduce($emailAddresses, function ($query, $emailAddress) {
return $query->orWhere('email', $emailAddress);
}, $query);
$queryWithPhoneNumbers = array_reduce($phoneNumbers, function ($query, $phoneNumber) {
return $query->orWhere('phone', $phoneNumber);
}, $queryWithEmailAddresses);
return $queryWithPhoneNumbers->get();
}
Both of these return every entry in the table.
Currently, the only method I've found that works is to query the database once for every email and every phone number which isn't ideal.
via SimpleJ