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

schir1964's avatar

Multiple orderBy on Query

Is there a way to set multiple orderBy criteria when querying from a model without chaining the commands.

Chaining (Works)

$result = $model->orderBy('name', 'asc')->orderBy('id', 'asc')->paginate(10);

No Chaining (Does not work)

$model->orderBy('name', 'asc');
$model->orderBy('id', 'asc');
$result = $model->paginate(10);

I'm receiving the sort criteria from table headers so chaining becomes difficult since the sort criteria changes (number of sort fields).

How is this handled generally?

0 likes
4 replies
Snapey's avatar

I think in your second example it's down to what you did before your code snippet in order to create $model

if you fetched the model (eg with find) then you are now working on, and sorting, a collection and not a query.

schir1964's avatar

After reading some more of the Eloquent documentation I discovered that a Dynamic Scope is normally used for this kind of thing. I created a dynamic scope to handle adding the Sort criteria one by one using the orderBy command. Basically it serves as a custom Query Builder command.

Dynamic Scope on Model

public function scopeOfSort($query, $sort)
{
    foreach ($sort as $column => $direction) {
        $query->orderBy($column, $direction);
    }

    return $query;
}

Dynamic Scope Usage

$results = $model->ofSort($sort_criteria)->paginate(10));

This worked as expected.

1 like
schir1964's avatar
schir1964
OP
Best Answer
Level 3

I discovered this on one of Jeffrey's videos that shows how to handle this outside of the model.

$model = (new Model)->newQuery();

foreach ($request->get('sort_criteria') as $column => $direction) {
    $model->orderBy($column, $direction);
}

$results = $model->paginate(10);
2 likes
Hesesses's avatar

Do you have ideas how to do this with collections?

Please or to participate in this conversation.