Laravel default orderBy

后端 未结 8 1793
离开以前
离开以前 2020-12-24 10:51

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,

8条回答
  •  死守一世寂寞
    2020-12-24 11:29

    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.

提交回复
热议问题