Search code examples
laraveleloquentlaravel-livewire

Laravel query isn't allowing me to query and where inside orWhere


I have laravel and laravel-livewire. Maybe it's overkill but I wanted to limit results to 10 or so and then have those 10 results filter to new results as the person typed out a name or phone number. The query works perfectly fine if I use just one of the statements. If I get rid of the phone and leave name it works, the same for getting rid of name and leaving phone. But if I have both like below it doesn't work. In the debug bar I see the query and it looks like what it should, but I don't get any results once I start typing.

$customers = DB::table('customers')->where('user_id', auth()->id())
    ->where(function($query) {
        $query->where('phone', 'like', '%'.$this->phone.'%')
            ->orWhere('name', 'like', '%'.$this->name.'%');
        })
    ->limit(10)
    ->get();

outputs query in debug bar

select * 
from `customers` 
where `user_id` = 12 
  and (`phone` like '%%' or `name` like '%%') 
limit 10`

Solution

  • You can try doing it like this

    $customers = DB::table('customers')->where('user_id', auth()->id())
    ->where(function($query) {
        $query->when(!is_null($this->phone), function ($q) {
               $q->where('phone', 'like', '%'.$this->phone.'%')
            })
            ->when(!is_null($this->name), function ($q) {
               $q->where('name', 'like', '%'.$this->name.'%')
            });
        })
    ->limit(10)
    ->get();