July, 13 2020
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.
<?php
// 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',
];
This package is has a trait DefaultOrderBy
that adds a default_order_by
global scope to the boot()
method of your Eloquent model.
<?php
...
protected static function boot()
{
parent::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.
Be the first to hear about anything I publish, launch, or think is helpful for you. Subscribe here
Litehost is a web hosting platform for PHP & Laravel developers with Composer, Git, PHP & CLI pre-installed. Try it now