Is there a clean way to enable certain models to be ordered by a property by default? It could work by extending the laravel\'s QueryBuilder, but to do so,
In Laravel 5.7, you can now simply use addGlobalScope inside the model's boot function:
use Illuminate\Database\Eloquent\Builder;
protected static function boot()
{
parent::boot();
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('created_at', 'desc');
});
}
In the above example, I order the model by created_at desc to get the most recent records first. You can change that to fit your needs.