i have a model and a relationship which i want to append a column from a relationship to the model so every time every where that the model is called that column from the relationship should be shown in model column .
i want to sort the model by that column and the second problem is that the column is updated_at
so if i can rename that to any other column name that would be very fine . so here is my relationship and model code :
my model :
JavaScript
x
public function statusHistory(){
return $this->hasMany(WishStatusHistory::class);
}
public function setUpdatedAtAttribute(){
$this->statusHistory->updated_at;
}
Advertisement
Answer
Create an accessor as below.
JavaScript
public function getNewUpdatedAtAttribute()
{
return $this->statusHistory->updated_at;
}
Then add the attribute name to the appends property on the model
JavaScript
protected $appends = ['new_updated_at']; // Modified column name. You can use any. make sure you update the same in method as well
To sort the results using appended column use sortBy
method. (https://laravel.com/docs/8.x/collections#method-sortby)
JavaScript
$model = Model::all();
$model = $model->sortBy(function($m){
return $m->new_updated_at;
});