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

Dicanio's avatar

Laravel default orderBy with one record always first

Hello, im looking for a way to solve my problem. I want to sort Role by it's name but keep specific one as first. For example if I have roles A, B, C, D i want to C be always first then others be ordered by name so the result would be C, A, B, D. And I want to keep this Role order in other models such as User

0 likes
8 replies
tykus's avatar

You can use orderByRaw like this

Role::orderByRaw("name = 'C', name")->get() 

I want to keep this Role order in other models such as User

Describe what you mean? Can a User have multiple roles? Or do you want to sort Users by their Role with C users always listed first?

Dicanio's avatar

@tykus I want to always sort this model, whether its Role::all() or $user->roles

Dicanio's avatar

@tykus and how can i choose if its ASC or DESC? tried fn ($q) => $q->orderByRaw("(name = 'C', name) DESC") but it doesnt seem to work //edit okay nvm, solved

tykus's avatar

@Dicanio each ordering expression gets its own order direction (although for the first one name = 'C', it doesn't make sense)

fn ($q) => $q->orderByRaw("name = 'C', name DESC")
Dicanio's avatar

@tykus yea, thanks a lot, but for some reason i had to write it this way fn ($q) => $q->orderByRaw("name, name = 'C") because otherwise it always was last

Dicanio's avatar

hmm, something is still wrong, if I choose your way

    protected static function booted()
    {
        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderByRaw("type = '1', type ASC");
        });
    }

Role with type 1 is always last, but if I use "type, type='1' its not ordered at all :(

tykus's avatar
tykus
Best Answer
Level 104

@Dicanio what am I thinking... type = '1' is a boolean (0 or 1) so you must order that part DESC

    protected static function booted()
    {
        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderByRaw("type = '1' DESC, type ASC");
        });
    }
1 like

Please or to participate in this conversation.