0

I've a customer and customer group table. I want to search the customers based on term/filter text.

Say, there is two customer_group_id, 7 and 8. When 8, I'll need to find mobile fields in orWhere clause, otherwise not.

What I've tried is

$contacts = Contact::where(function ($query) use ($term) {
    $query->where('contacts.name', 'like', '%' . $term .'%')
});

// For customer_group_id=8
$contacts->when('customer_group_id=8', function($q) use ($term){
    return $q->orWhere('mobile', 'like', '%' . $term .'%');
});

The when() is not working. It showing all the results. I know that I've to pass any boolean value in the when() functions first parameter.

Is there any solution for this problem? Or what is the other way I can get the data's.

9
  • What table is the mobile field in? Commented May 26, 2019 at 7:12
  • it is in the contacts table Commented May 26, 2019 at 7:14
  • a not empty string is always true Commented May 26, 2019 at 7:17
  • yes, I know that customer_group_id=8 is true, I know it is not the way. I just want this by anyway Commented May 26, 2019 at 7:18
  • 1
    So you only want to add the orWhere condition if customer_group_id=8 Commented May 26, 2019 at 7:20

1 Answer 1

1

The when() method doesn't add an if statement to your query, it is just a way to save you from writing an if statement in your code.

To achieve what you're after you can use nested orWhere() clause:

$contacts = Contact::where('name', 'like', '%' . $term . '%')
    ->orWhere(function ($query) use($term) {
        $query->where('customer_group_id', 8)->where('name', 'like', '%' . $term . '%');
    })
    ->get();

If there is more to your query than what you've put in your question then you can simply wrap the above in another where clause:

$contacts = Contact::where(function ($query) use ($term) {
    $query->where('name', 'like', '%' . $term . '%')
        ->orWhere(function ($query) use ($term) {
            $query->where('customer_group_id', 8)->where('name', 'like', '%' . $term . '%');
        });
})
    ->where('some column', 'some value')
    ->get();
Sign up to request clarification or add additional context in comments.

Comments

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.