laravel orderBy() filter
I'm using the current code to provide a filter / sort option to my users searching for items:
//attach sort filter if requested
if($request->filled('sort')){
//popularity by most views
if($request->sort == 'mostViews')
$product->withCount('views')->orderByDesc('views_count');
//price low to high
if($request->sort == 'priceAsc')
$product->orderBy('usd_price');
//price high to low
if($request->sort == 'priceDesc')
$product->orderByDesc('usd_price');
}
//fetch results
$searchResults = $product->paginate(15);
Is there a way I can make sure the items where is_promoted are always listed at the top (meaning they somehow bypass the orderBy()options?
@t0berius
doing a subsequent sort by that field should solve this
//fetch results
$searchResults = $product->orderBy('is_promoted')->paginate(15);
@automica
Will the order make a difference?
For example:
@t0berius doing a subsequent sort by that field should solve this
//fetch results
$searchResults = $product->latest()->orderBy('is_promoted')->paginate(15);
against
$searchResults = $product->orderBy('is_promoted')->latest()->paginate(15);
@t0berius
maybe this can help you
$product->orderByDesc('is_promoted');
if($request->filled('sort')){
//popularity by most views
if($request->sort == 'mostViews')
$product->withCount('views')->orderByDesc('views_count');
//price low to high
if($request->sort == 'priceAsc')
$product->orderBy('usd_price');
//price high to low
if($request->sort == 'priceDesc')
$product->orderByDesc('usd_price');
}
//fetch results
$searchResults = $product->paginate(15);
@a4ashraf Will the order of how I use ->orderByDesc('is_promoted') be relevant (before or after the sort filters)?
@t0berius
can you share this complete function and migration?
@a4ashraf Just take a look to my second post above.
@t0berius
try with this
if will sort first is_promoted and then other columns
if($request->filled('sort')){
//popularity by most views
if($request->sort == 'mostViews')
$product->withCount('views')->orderByDesc('is_promoted', 'views_count');
//price low to high
if($request->sort == 'priceAsc')
$product->orderByDesc('is_promoted')->orderBy('usd_price');
//price high to low
if($request->sort == 'priceDesc')
$product->orderByDesc('is_promoted', 'usd_price');
}
//fetch results
$searchResults = $product->paginate(15);
Please or to participate in this conversation.