0

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.

0

1 Answer 1

2

You orWhere condition is inside another where so I imagine it won't work as expected.

I would suggest changing your whereHas to orWhereHas and then changing the orWhere inside it to where:

$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->orWhereHas('company', function ($query) use ($searchWildcard) {
        $query->where('name', 'LIKE', $searchWildcard);
    });
})->when(in_array('name', $searchFilters), function ($query) use ($searchWildcard) {
    $query->orWhere('name', 'LIKE', $searchWildcard);
});
Sign up to request clarification or add additional context in comments.

1 Comment

@BvdL Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.