1
votes

I want to add a key while I'm getting any response of an API using Models in laravel,

Currently, I'm developing an API to get a response with a new one key to add to dynamically.

3
how do u call the listing API?TsaiKoga
with the relation of is_favorite key.Vikas Ukani
@VikasUkani show how you are calling relation? Need some code to debug.Prashant Deshmukh.....
what u want add in the extra field?Vikas Katariya
@VikasKatariya I want to add a new column in my listing API, But that key doesn't exist in my databaseVikas Ukani

3 Answers

1
votes

If I'm not wrong I guess you are trying to create a new field which is not present in table but need to be created dynamically with some logic inside it and you want to pass that field to each and every product of yours.

If so than I guess Laravel Eloquent Accessor will be a best option to use in this case. With the help of Accessor you can create any kind of field and can call it as same as we are calling others fields.

for more reference please take a look at this https://laravel.com/docs/5.7/eloquent-mutators Laravel Documentation.

A sample picked from Laravel Documentation.

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

Now I can use full_name inside my controller or blade files like $user->full_name and than it will give me the concatenated string of first_name and last_name.

1
votes

Add the attribute to $appends.

class MyModel extends Model {
    ...    
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['extra'];
    ...
}
1
votes

first of all in your model add this to add custom field

protected $appends = ['is_favorite'];

public function getIsFavoriteAttribute($value)
{
    return $this->name;  // whatever you want add here
}

But it problem while you getting other models details while applying relations and select from relation.