stephenjude/default-model-sorting
composer require stephenjude/default-model-sorting
use Stephenjude\DefaultModelSorting\Traits\DefaultOrderBy; to your Eloquent model.
class Article extends Model
{
use DefaultOrderBy;
protected static $orderByColumn = 'title';
}
$articles = Article::all(); // Automatically ordered by `title` ASC
DefaultOrderBy trait in stephenjude/default-model-sorting/src/Traits/DefaultOrderBy.php.$orderByColumn and $orderByColumnDirection in your model.php artisan vendor:publish --provider="Stephenjude\DefaultModelSorting\ServiceProvider" to inspect default settings.class Post extends Model
{
use DefaultOrderBy;
protected static $orderByColumn = 'published_at';
protected static $orderByColumnDirection = 'desc';
}
Post::orderBy('views', 'desc')->get(); // Ignores default
protected static $orderByColumn = function() {
return request()->wantsJson() ? 'id' : 'title';
};
public function scopeActive($query)
{
return $query->where('is_active', true)->orderByDefault();
}
$model = new class extends Model {
use DefaultOrderBy;
protected static $orderByColumn = 'test_column';
};
// config/default-model-sorting.php
'default_column' => 'created_at',
'default_direction' => 'asc',
class Comment extends Model
{
use DefaultOrderBy;
protected static $orderByColumn = 'created_at';
}
SoftDeletes trait.orderBy().orderByDefault() to reapply defaults:
Post::orderBy('views')->orderByDefault()->get();
$orderByColumn may cause performance overhead if called repeatedly.order or asc may conflict with Laravel’s query builder.protected static $orderByColumn = '"order"';
with().$query = Post::toSql(); // Inspect generated SQL for ORDER BY clauses
use DefaultOrderBy to isolate issues.DB::enableQueryLog();
Post::all();
dd(DB::getQueryLog());
protected static function bootDefaultOrderBy()
{
static::addGlobalScope(new class extends Scope {
public function apply(Builder $builder, Model $model)
{
if (!$builder->getQuery()->orders) {
$builder->orderByDefault();
}
}
});
}
$orderByColumn:
protected static function boot()
{
static::retrieved(function ($model) {
if (auth()->check()) {
static::$orderByColumn = 'user_id';
}
});
}
ALTER TABLE posts ORDER BY title ASC;
(Note: This is database-specific and may not work with all setups.)$orderByColumn) take precedence.Post::resetOrderByColumn();
How can I help you explore Laravel packages today?