Search code examples
laravellaravel-5laravel-5.3laravel-5.4

Laravel search logic


For the past two days I was trying to build this relatively simple search system but I just can't figure this out.. Basically, I have a few select tags which contain options to filter the users.. Something like this:

  <div class="col-sm-4">
    <label for="price">Price:</label><br>
    <select class="browse-select" name="price">
      <option>Any</option>
      <option value="1">Less than 100$</option>
      <option value="2">More than 100$</option>
    </select>
  </div>

  <div class="col-sm-4">
    <label for="delivery">Delivery:</label><br>
    <select class="browse-select" name="delivery">
      <option>Any</option>
      <option value="1">1 month or less</option>
      <option value="7">7 days or less</option>
      <option value="3">3 days or less</option>
    </select>
  </div>

Those are in a form (get request form) and here's my controller.

public function index(Request $request){

  $users = User::paginate(10);
  $service = Service::all();

  //Search Logic

  $category = $request->input('category');
  $price = $request->input('price');
  $delivery = $request->input('delivery');

  $searchQuery = Service::with('user');

  $searchQuery->where('category','=',$category);

  if ($price == 1) { //price input has a value of 1 which means (less than 100)
    $searchQuery->where('price','<',100)->where('category','=',$category);
  }elseif($price == 2){
    $searchQuery->where('price','>',100)->where('category','=',$category);
  }

  $result = $searchQuery->get();

  return view('browse.index', compact('users','service','result'));
}

As you can see I have a relationship between Users and Services. Because I need to access user's services in order to compare the values and query the database.

What I have so far, works but only for one select. If I select a category, that works fine and the user is displayed. But, if I try for example to choose a category and also a price then it returns all the users. How should I do this properly? I feel like I'm missing something here..


Solution

  • I believe you need to add additional checks and split your query. Something like

    $searchQuery = Service::with('user');
    
    if($request->has('category'))
    {
        $searchQuery->where('category', $request->input('category'));
    }
    
    if($request->has('price'))
    {
        $operator = (1 === $request->input('price')) ? '>' : '<';
    
        $searchQuery->where('price', $operator, 100);
    }
    
    $result = $searchQuery->get();