Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

t0berius's avatar

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?

0 likes
7 replies
automica's avatar

@t0berius doing a subsequent sort by that field should solve this

    //fetch results
    $searchResults = $product->orderBy('is_promoted')->paginate(15);
t0berius's avatar

@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);
a4ashraf's avatar

@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);
t0berius's avatar

@a4ashraf Will the order of how I use ->orderByDesc('is_promoted') be relevant (before or after the sort filters)?

a4ashraf's avatar

@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.