udemethegrtman udemethegrtman - 12 days ago 8
PHP Question

orWhere issues in search

Hi am searching my dashboard features


  • CATALOGUE STYLES

  • SAVED STYLES



The catalogue style is working perfectly but the saved style is searching based on the user, is there a way where is a andWhere() to search where(something) and where(another thing) in laravel.

public function search(){

$wsSearch = Input::get('search');

$term = $wsSearch;

// search catalogue style

$searchedCatalogueStylesCount = Cataloguestyle::where('catalogue_style_name','LIKE','%'.$term.'%')
->orWhere('catalogue_categories','LIKE','%'.$term.'%')
->orWhere('catalogue_style_description','LIKE','%'.$term.'%')
->orWhere('catalogue_sub_categories','LIKE','%'.$term.'%')
->count();

$searchedCatalogueStyles = Cataloguestyle::where('catalogue_style_name','LIKE','%'.$term.'%')
->orWhere('catalogue_categories','LIKE','%'.$term.'%')
->orWhere('catalogue_style_description','LIKE','%'.$term.'%')
->orWhere('catalogue_sub_categories','LIKE','%'.$term.'%')
->paginate(50);

// search saved style

$searchedSaveStylesCount = Savestyle::where('user_id',Auth::user()->id)
->orWhere('catalogue_style_name','LIKE','%'.$term.'%')
->orWhere('catalogue_categories','LIKE','%'.$term.'%')
->orWhere('catalogue_style_description','LIKE','%'.$term.'%')
->orWhere('catalogue_sub_categories','LIKE','%'.$term.'%')
->count();

$searchedSaveStyles = Savestyle::where('user_id',Auth::user()->id)
->orWhere('catalogue_style_name','LIKE','%'.$term.'%')
->orWhere('catalogue_categories','LIKE','%'.$term.'%')
->orWhere('catalogue_style_description','LIKE','%'.$term.'%')
->orWhere('catalogue_sub_categories','LIKE','%'.$term.'%')
->paginate(50);

Session::flash('searchTerm',$term);

// return Redirect::to('/search')
return view('main_app.dashboard.search')
->with(['searchedCatalogueStyles' => $searchedCatalogueStyles,
'searchedSaveStyles' => $searchedSaveStyles,
'searchedCatalogueStylesCount' => $searchedCatalogueStylesCount,
'searchedSaveStylesCount' => $searchedSaveStylesCount
]);

}


If you look closely at the
$searchedSaveStyles
variable, you will see
where('user_id',Auth::user()->id)
, we want it to be a and the following where statements not or, how do we do that?

Answer

If you want it so that all the OR WHERE's are grouped then you would put them inside a WHERE with a function, like so:

$searchedSaveStyles = Savestyle::where('user_id',Auth::user()->id)
  ->where(function($q) {
    $q->orWhere('catalogue_style_name','LIKE','%'.$term.'%')
      ->orWhere('catalogue_categories','LIKE','%'.$term.'%')
      ->orWhere('catalogue_style_description','LIKE','%'.$term.'%')
      ->orWhere('catalogue_sub_categories','LIKE','%'.$term.'%');
  })->paginate(50);