Laravel default orderBy

Laravel default orderBy

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Default OrderBy in Laravel Models Without Rewiring QueryBuilder

One of the most common friction points when working with frequently reused models is handling data ordering. If you have a model that is queried across multiple controllers, services, or repositories, and you always need to sort results by a specific column, the standard approach often feels clunky. You find yourself appending .orderBy('column', 'desc') or invoking a closure every single time. While functional, this repetition violates the DRY principle and makes it easy to forget to sort in a specific edge case.

The naive solution suggested in many forums is to extend the Illuminate\Database\Eloquent\Builder class. This involves overriding methods like orderBy, get, or even select. However, as experienced engineers know, rewiring core framework features is generally bad practice. It tightens coupling to your application's specific logic inside Laravel's engine, making upgrades difficult and introducing subtle bugs into the query building process itself.

A cleaner, more maintainable approach exists that leverages Laravel's existing scope system without touching the QueryBuilder inheritance chain. The strategy involves defining a dedicated property on the model itself to store the default sorting configuration, then exposing that logic through scopes.

Implementing Default Sorting Properties

The core idea is to treat the default order by as a class-level property rather than a method argument. By adding $orderBy and $orderDirection properties directly to your model class, you can centralize this configuration.

Here is how you define these properties and expose them via scopes:

protected $orderBy = 'created_at';
protected $orderDirection = 'DESC';

public function scopeOrdered($query)
{
    if ($this->orderBy) {
        return $query->orderBy($this->orderBy, $this->orderDirection);
    }

    return $query;
}

public function scopeGetOrdered($query)
{
    return $this->scopeOrdered($query)->get();
}

The scopeOrdered method acts as a guard. It checks if the $this->orderBy property has been set (or rather, if it is not null/empty in your specific context). If a default order exists, it applies it to the query builder instance passed into the scope. The conditional check ensures that you can still override this behavior if needed, or simply skip sorting if no default is defined, though typically you would set the property once per model.

The scopeGetOrdered method combines the sorting logic with the actual retrieval of results. This allows for a concise syntax in controllers while keeping the heavy lifting inside the model.

Using Scopes with Eager Loading

One of the most common pitfalls when implementing default ordering is forgetting that scopes can be chained onto eager-loaded relations. In your model, you might define a relationship like belongsToMany and want those related models to also respect a default sort order.

public function anotherModel()
{
    return $this->belongsToMany('SomeModel', 'some_table')->ordered();
}

Notice the .ordered() call on the relation definition. Because we defined the scope as public and attached it to the query builder, any relationship that returns a collection or model using this scope will inherit the default sorting logic automatically. This is crucial when you are eager loading data in controllers where you might not explicitly want to sort the parent collection but definitely want the related collections sorted.

Applying the Logic in Controllers

Once the model is configured, usage becomes trivial and consistent. You no longer need to repeat the ordering syntax in every controller method.

// Retrieve all models with their eager-loaded relations, automatically sorted
$models = MyModel::with('anotherModel')->getOrdered();

// Or, if you only need the first record (e.g., for a "latest" view)
$latest = MyModel::with('anotherModel')
    ->ordered()
    ->first();

This pattern effectively solves the problem of a model being heavily reused by many others. Everyone who uses this model and does not provide custom sorting options will receive records sorted by the default option defined in the class properties. It removes the cognitive load of remembering to add .orderBy() to every query, while still allowing for easy overrides when necessary (e.g., $query->ordered()->where(...)->get()).

By keeping the logic within the model and avoiding inheritance from the QueryBuilder, you maintain a clean separation of concerns. The framework handles the query building, your model handles its specific data contracts, and your controllers remain focused on business logic rather than SQL syntax details.

Our network