Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Developer654079525's avatar

Ordering

Should relationships in models be ordered ? Is this a valid scenario or should the ordering be performed elsewhere:


class Category extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'parent_id', 'slug', 'position'];

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id')
          ->orderBy('position');
    }

    public function posts()
    {
        return $this->hasMany(Post::class)
          ->orderBy('position');
    }
}

The category table has a self-referencing parent category.

0 likes
3 replies
jlrdw's avatar

If having several orderBy possibilities you could look into query scopes.

Glukinho's avatar

The only recommendation comes to mind is that sorting happens in query builder, not on already fetched collection - let database do database's work.

1 like
martinbean's avatar

@glukinho For cases like this, I’ll create a trait that automatically applies a global scope, so that the scope can be removed if I don’t want records ordering for whatever reason (i.e. listed by last updated date).

Sorting is something I’ve previously created a trait/scope around. My trait/scope looks like this:

class SortingScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->orderBy($model->getPositionColumn());
    }

    public function extend(Builder $builder)
    {
        $builder->macro('withoutSorting', function (Builder $builder) {
            return $builder->withoutGlobalScope($this);
        });
    }
}

Please or to participate in this conversation.