Maniruzzaman Akash
Maniruzzaman Akash

Reputation: 5025

Laravel Eloquent - Conditional Data Fetching

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.

Upvotes: 0

Views: 357

Answers (1)

Rwd
Rwd

Reputation: 35180

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

Upvotes: 1

Related Questions