0
votes

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.

1
What table is the mobile field in? - Rwd
it is in the contacts table - Maniruzzaman Akash
a not empty string is always true - porloscerros Ψ
yes, I know that customer_group_id=8 is true, I know it is not the way. I just want this by anyway - Maniruzzaman Akash
So you only want to add the orWhere condition if customer_group_id=8 - Rwd

1 Answers

1
votes

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();