Laravel search query with multiple conditions

后端 未结 3 814
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-31 05:52

Newbie to PHP/Laravel here so please be patient.

I have a webpage that is searching based on 3 criteria for dogs , breed, sex and radius.

here is the relevant co

3条回答
  •  野的像风
    2021-01-31 06:14

    You can use query scopes http://laravel.com/docs/eloquent#query-scopes to make it verbose and easier in your controller (or wherever you will be doing it in future) then chain them according to your needs:

    // Dog model
    public function scopeSearchBreed($query, $breed)
    {
      $query->whereHas('breed', function ($q) use ($breed) {
        $q->where('name', 'like', "%{$breed}%");
      });
    }
    
    public function scopeWithinRadius($query, $radius)
    {
      $query->where(...); // do math here
    }
    

    Then all you need is this:

    public function index()
    {
      $q = Dog::query();
    
      if (Input::has('search'))
      {
         // simple where here or another scope, whatever you like
         $q->where('name','like',Input::get('search'));
      }
    
      if (Input::has('search-breed'))
      {
         $q->searchBreed(Input::get('search-breed'));
      }
    
      if (Input::has('sex'))
      {
         $q->where('sex', Input::get('sex'));
      }
    
      if (Input::has('radius'))
      {
         $q->withinRadius(Input::get('radius'));
      }
    
      $dogs = $q->orderBy(..)->paginate(5);
    
      // ...
    

提交回复
热议问题