NewbieCoder
NewbieCoder

Reputation: 35

Laravel search filtering cannot single filter

I have multiple dropdown search filter. I can filter all the column of my table if only I select every dropdown. If I'm only selecting one of them or two, it doesn't return any result. Is there anything to add or did I do it wrongly?

Eloquent

$query = Table::when($id, function($q) use ($id){
                return $q->where('id', $id);
            })
            ->when($state, function($q) use ($state){
                return $q->where('state', $state);
            })
            ->when($country, function($q) use ($country){
                return $q->where('country', $country);
            })
            ->when($name, function($q) use ($name){
                return $q->where('name', $name);
            })
            ->when($city, function($q) use ($city){
                return $q->where('city', $city);
            })
            ->when($status, function($q) use ($status){
                return $q->where('status', $status);
            })
        ->paginate(10);

return $query;

Controller

if ($request->id || $request->state || $request->country|| $request->name || $request->city || $request->name || $request->status){
      $filter = $eloquent->getTable($request->id, $request->state, //all request);
}
else{
     $filter = $eloquent->all();
}

Or is there any other way that can be done? Guide and help will be appreciated.

Upvotes: 1

Views: 675

Answers (2)

yecademy
yecademy

Reputation: 37

Try this:

$query = Model::query();

if(isset($id))
 $query->where('id', $id);
if(isset($state))
 $query->where('state', $state);
if(isset($country))
 $query->where('country', $country);
if(isset($name))
 $query->where('name', $name);
if(isset($city))
 $query->where('city', $city);
if(isset($status))
 $query->where('status', $status);
return $query->paginate(10);
 

Upvotes: 1

archvayu
archvayu

Reputation: 448

declare your query first then you can climb up the condition tree from the lowest value from your dropdown selections;

$query = Table::when($status, function($q) use ($status){
            return $q->where('status', $status);
        });

if(isset($city)) {
    $query = $query->when($city, function($q) use ($city) {
                 return $q->where('city', $city);
             });
}

if(isset($name)) {
    $query = $query->when($name, function($q) use ($name) {
                 return $q->where('name', $name);
             });
}
// climb up the condition tree you want to check from least dependent variable to most dependent variable
...
...
// return filtered results
return $query->paginate(10);

Upvotes: 0

Related Questions