php - how to append a column to a model from a relationship laravel

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 isupdated_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 :
public function statusHistory(){
return $this->hasMany(WishStatusHistory::class);
}
public function setUpdatedAtAttribute(){
$this->statusHistory->updated_at;
}
Answer
Solution:
Create an accessor as below.
public function getNewUpdatedAtAttribute()
{
return $this->statusHistory->updated_at;
}
Then add the attribute name to the appends property on the model
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 usesortBy
method. (https://laravel.com/docs/8.x/collections#method-sortby)
$model = Model::all();
$model = $model->sortBy(function($m){
return $m->new_updated_at;
});
Answer
Solution:
maybe you could try this in your model:
public function getUpdatedAtAttribute()
{
return $this->statusHistory->updated_at;
}
// then;
$model->updated_at;
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: can't write image data to path
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.