Search code examples
phplaravel-5eloquentlumen

Setting default order for all the tables in a database using lumen


I have a complete application which is written using lumen. The application is complete. I just need to add order by clause with each query in the application which is somehow time taking to add. After searching everywhere I found the following method.

protected static function boot() {
    parent::boot();
    static::addGlobalScope('order', function (Builder $builder) {
    $builder->orderBy('date', 'desc');
   });
}

I shall have to add above function in each model. This is also a reasonable solution but I do not want to do this. I want to add this function on a single place rather than adding in each model like in any service provider or somewhere else.I am not much familure with this framework. Please, help if any one knows about its solution. Please, note that the timestamp field names for order by has different prefix. Eg. tbl_created_at is the Created_at field in a table named column and prnt_created_at field is Created_at field in a table named prints. Thanks for any help.


Solution

  • Make it a trait, in the trait you can still use the methods and variables from class that is using the trait:

    <?php
    namespace App\Traits;
    
    trait DefaultOrderByDate
    {
        protected static function boot() {
            parent::boot();
    
            $field = parent::CREATED_AT;
    
            static::addGlobalScope('order', function (Builder $builder) use ($field) {
                $builder->orderBy($field, 'desc');
            });
        }
    }
    

    Now in your models you can use them like:

    <?php
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use App\Traits\DefaultOrderByDate;
    
    class SomeModel extends Model
    {
       use DefaultOrderByDate;
    
        /**
         * The name of the "created at" column.
         *
         * @var string
         */
        const CREATED_AT = 'prnt_created_at';
    
        /**
         * The name of the "updated at" column.
         *
         * @var string
         */
        const UPDATED_AT = 'prnt_updated_at';
    }