Search code examples
phparrayseloquentmodellaravel-4

Exclude all except specified attributes in query - Eloquent Laravel 4.2


In Laravel 4.2, the following Eloquent query will remove the attributes that are specified in the array. I want to do a similar operation in which I exclude all attributes by default and only include the ones that are in an array. How can I do this? I suspect that the answer may have something to do with defining a custom $appends array on the model before running the query, but I don't know how to do this.

return MyModel::all()->each(function($row) {
    $row->setHidden([
        'attribute_1',
        'attribute_2'
    ]);
});

Solution

  • In your model

    protected $excludedColumns = ['attr1', 'attr2'];
    
      public function scopeExcludeColumns($query) {
            return $query->select(array_diff(Schema::getColumnListing($this->table), $this->excludedColumns));
        }
    

    Use:

    $result = Model::excludedColumns()->all();
    

    another option is to setup $hidden property on model by folowing

    protected $hidden = array('attr1','attr2');
    

    but it will exclude this fields from model only when call $result->toArray; or $result->toJson();