I am using Laravel 4.2
.
I have two models: User
and Video
, both of these models are having one-to-many relationship
i.e. User -> HasMany-> Video
.
Recently, I got a requirement to display the list of users along with sum of file-size of total videos uploaded by each user and allow users to be order by the sum of file size ascending or descending.
I've made following changes in User
model:
class User extends Eloquent {
protected $hidden = array('videosSum');
protected $appends = array('videos_size');
public function videosSum() {
return $this->hasOne('Video')
->selectRaw('sum(file_size) as sum, user_id')
->groupBy('user_id');
}
public function getVideosSizeAttribute()
{
// if relation is not loaded already, let's do it first
if ( ! array_key_exists('videos_size', $this->relations)){
$this->load('videosSum');
}
$related = $this->getRelation('videosSum');
return $this->attributes['videos_size'] = isset($related->sum) ? (int) $related->sum : 0;
}
}
And using like:
User::where('id', '!=', Auth::user()->id);
I am getting the desired result.
But the problem is, I don't want the videos_size
attribute everywhere, where the User
model gets called. I want to set it dynamically.
I tried User::$appends = ['videos_size']
but it gives protected property cannot be set outsize of class error.
I also tried to make a method in User
model which set the $appends
if called, but it is also not working.
Can anybody help me how to enable the appends property dynamically?