Skip to content
Advertisement

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 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

Advertisement

Answer

Create an accessor as below.

JavaScript

Then add the attribute name to the appends property on the model

JavaScript

To sort the results using appended column use sortBy method. (https://laravel.com/docs/8.x/collections#method-sortby)

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement