Hi,
I need to pass some 'virtual' fields to my model when passing JSON. I've started with the very basic according to the docs (https://laravel.com/docs/5.3/eloquent-serialization#appending-values-to-json) but actually I cannot make it work.
class Ibattribute extends Model
{
protected $appends = ['ident'];
protected $fillable = ['name', 'value','optional'];
public function getIdentAttribute()
{
// return $this->name.'_'.$this->optional;
return 'additional_attribute';
}
public function installedbase()
{
return $this->belongsTo('App\InstalledBase', 'foreign_key', 'other_key');
}
}
However when accessing e.g App\Ibattribute::first(); the additional "ident" attribute is not added,
>>> App\Ibattribute::first()
=> App\Ibattribute {#689
id: 1,
installedbase_id: 15,
name: "Megis",
value: "1",
optional: "G",
created_at: "2016-10-03 08:12:15",
updated_at: "2016-10-03 08:12:15",
}
but explicit call to attribute works fine
>>> App\Ibattribute::first()->ident
=> "additional_attribute"
I'm using laravel 5.3.6. Any tips would be appreciated! Thanks!
Appends is for serializing the model. You haven't done anything involving serializing ... toArray
toJson
etc.
So what shall I do to add some "virtual fields" to be able to then pass it to view by "compact"?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community