I am trying to create a conditional User search function. There are three filters that a user could select to search on:
- user name
- company name associated with user
- role name associated with user
In the following example I have put all the filters in the array $searchFilters for simplicity.
I only want Laravel to search the filters that are present in the array.
The code
$q = request()->q;
$searchWildcard = '%' . $q . '%';
$searchFilters = ['name', 'roles', 'company'];
$users = User::when(in_array('roles', $searchFilters), function ($query) use ($searchWildcard) {
$query->whereHas('roles', function($query) use ($searchWildcard) {
$query->where('name', 'LIKE', $searchWildcard);
});
})->when(in_array('company', $searchFilters), function($query) use ($searchWildcard) {
$query->whereHas('company', function($query) use ($searchWildcard) {
$query->orWhere('name', 'LIKE', $searchWildcard);
});
})->when(in_array('name', $searchFilters), function($query) use ($searchWildcard) {
$query->orWhere('name', 'LIKE', $searchWildcard);
});
The first part of the query works: It retrieves the roles based on the search query by the user, but it doesn't work for the company name or user name.
Edit
It only doesn't work for the company name.