Change Default Sorting in Laravel Eloquent with a Global Scope

As a Laravel developer, you probably already know that sorting data in an Eloquent model is a common task. By default, Eloquent orders records based on their primary key. However, did you know that you can easily change the default sorting order using a global scope? This can be a helpful little tip that saves you time and makes your code more maintainable.

To implement this feature, you can define a global scope that sorts records based on a specific field. For example, let's say you have a Post model and you want to sort posts by their published_at field by default. You can add the following global scope to your Post model:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('published_at', function (Builder $builder) {
        $builder->orderBy('published_at');
    });
}

Now, whenever you fetch posts using Eloquent, they will be ordered by their published_at field by default. This approach can help you avoid repetitive sorting code and make your application more consistent.

Clicky