Support the ongoing development of Laravel.io →
Requests Eloquent

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!

Last updated 2 years ago.
0

Appends is for serializing the model. You haven't done anything involving serializing ... toArray toJson etc.

0

So what shall I do to add some "virtual fields" to be able to then pass it to view by "compact"?

0

Sign in to participate in this thread!

Eventy

Your banner here too?

visualus visualus Joined 16 Sep 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.