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

isong1234's avatar

how to use order by with condition in laravel?

Scenario: supposed i have data, where status is completed, now i want status completed displayed at the bottom, otherwise the most recent created displayed at the top, how can you query it using orderBY or any method in laravel? pls help im new in laravel thank you..

This is the query i tried: // The list of completed surveys is displayed at the bottom. Otherwise, the most recent date of creation is displayed at the top.

        $surveys = $query->select('surveys.*')
            ->orderBy("status", 'asc')
            ->get();
0 likes
2 replies
asathler's avatar

Hi @isong1234

You may change your code a little bit, like so:

$surveys = $query->table('surveys')
    ->where('active', true)
    // ->select('*') // it's default behavior
    ->orderBy('status', 'asc')
    ->get();

It combines where and orberBy through Eloquent.

...and check the laravel documentation quoted above by @jlrdw.

Hope to helped

2 likes

Please or to participate in this conversation.