I want to make products to be ordered according to each user request as code below and here is the code
$pagination = Session::get('page'); if(Session::get('page') == NULL){ Session::put('page',12); } if($request->has('per_page')){ Session::put('page',$request->per_page); $pagination = Session::get('page'); } $pris = product_categories::where('category_id', $id)->pluck('product_id')->toArray(); $products = Product::whereIn('id' , $pris)->paginate($pagination); $pagination = Session::get('page'); if($request->get('sort') == 'price_asc'){ $products = $products->OrderBy('price','asc'); }elseif($request->get('sort') == 'price_desc'){ $products = $products->OrderBy('price','desc'); }elseif($request->get('sort') == 'popular'){ $products = $products->OrderBy('views','desc'); }elseif($request->get('sort') == 'newest'){ $products = $products->OrderBy('created_at','desc'); }
it return error orderby doesn’t exist on collection
Advertisement
Answer
Your orderBy()
statements have to be added to the query before you run paginate:
$productsQuery = Product::whereIn('id' , $pris); //$pagination = Session::get('page'); // not sure why this line is there? if($request->get('sort') == 'price_asc'){ $productsQuery ->OrderBy('price','asc'); }elseif($request->get('sort') == 'price_desc'){ $productsQuery ->OrderBy('price','desc'); }elseif($request->get('sort') == 'popular'){ $productsQuery ->OrderBy('views','desc'); }elseif($request->get('sort') == 'newest'){ $productsQuery ->OrderBy('created_at','desc'); } $products = $productsQuery->paginate($pagination);