Skip to content
Advertisement

can i add new key in models?

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.

Advertisement

Answer

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.

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