Getting Started With Default Sorting In Your Eloquent Models

Published July 13, 2020 • 2 mins read

Default Model Sorting package is a mini Laravel package I published recently. By default, Laravel Eloquent models return queries that are ordered by the id column of the model table.

With this package, you can set default order by in your Eloquent model so you don't have to call the orderBy Eloquent builder.

// without default-model-sorting
Article::orderBy('title', 'asc')->get(); //sorted by the title

//using default-model-sorting
Article::all(); // sorted by the title


First you have to install this package via composer.

composer require stephenjude/default-model-sorting


Using the DefaultOrderBy trait of this package, you can set the default column you want to sort by.

For example, if you want to set the default order column for Article model (assuming you are building a blog). You will use the DefaultOrderBy trait and set the $orderByColumn property inside your Article model.

use Stephenjude/DefaultModelSorting/Traits/DefaultOrderBy;

class Article extends Model
    use DefaultOrderBy;

    protected static $orderByColumn = 'title';

Now your Article model queries will be ordered by title column in ascending order.

You can also set the $orderByColumnDirection property. This property is set to asc as the default value.

protected static $orderByColumnDirection = 'asc';

To set the global default $orderByColumnDirection property, publish the package configuration file.

php artisan vendor:publish --provider="Stephenjude\DefaultModelSorting\DefaultModelSortingServiceProvider" --tag="config"

Now you can update the configuration file as you desire.

// config/default-model-sorting.php
return [    
    /*  Default Sorting Order */
    'order_by' => 'asc',

Under The Hood

This package is has a trait DefaultOrderBy that adds a default_order_by global scope to the boot() method of your Eloquent model.

 protected static function boot()

     // Default order by column
     $column = Self::$orderByColumn;

     // Use the default order by on the config if its not set
     $direction = isset(Self::$orderByColumnDirection)
            ? Self::$orderByColumnDirection
            : config('default-model-sorting.order_by');
     // Add default order by column to any Eloquent model that uses this trait
     static::addGlobalScope('default_order_by', function (Builder $builder) use ($column, $direction) {
            $builder->orderBy($column, $direction);

If you don't want to use the package, you can add this code to your Eloquent model.

If you find this package helpful please give it a start on Github.

Hey, have you tried Litehost lately?

Litehost is my side project which is a shared hosting platform with PHP & Laravel developers in mind. It has Composer, Git & PHP CLI pre-installed on its servers. SSH access is also granted on request. Litehost is pretty affordable. Try it today.