Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent : How to generate a fake column in a Json response?

I have two models: Uai and Information with an hasOne relationship.

Uai (uai_id, a)
Information (uai_id, b)

I want to generate a Json response witch contains :

  • all the Uai records
  • a "fake" column whitch says true if the hasOne Relationship exists between Uai and Information and false if there is no relationship

Any idea ?

Thanks in advance Paguemaou

Edit One Thanks jedrzej.kurylo for your answer. How can I use the uai_id of the current row in the fake column getter ? I othen use getters and seeters but I never try to use the content of another column. Can you give me an example ?

If I understand, I can use the fake column name in a select like others columns name. I am true ?

like image 551
Paguemaou Avatar asked Mar 13 '23 22:03

Paguemaou


1 Answers

Eloquent allows you to easily add custom field to a model's JSON representation.

Firstly, you need to define a list of additional fields by defining $appends property in your model class:

protected $appends = ['fakeColumnName'];

Secondly, add a getter for the fake column that will provide the value for custom column:

public function getFakeColumnNameAttribute() {
    //here add the code that will return custom column's value
}
like image 139
jedrzej.kurylo Avatar answered Apr 25 '23 04:04

jedrzej.kurylo