Support the ongoing development of Laravel.io →
Eloquent Architecture

The model:

class Item extends Eloquent {
	
	public function getCentsAttribute()
	{
		 return substr($this->attributes['price'], -2);
	}
	
}

A test route:

Route::get('cents', function()
{
	$item = Item::find(1);
	$attr = 'cents';
	
	$direct = $item->{$attr};
	$helper = object_get($item, $attr);
	
	return compact('direct', 'helper');
});

The response:

{"direct":"99","helper":null}

Accessing the dynamic attribute from inside the object_get helper function returns null.
After some debugging I found that the model's __get() method is not called at all when the object is accessed inside the helper function (even if internally it really goes the same as $item->{$attr}).
Could please someone explain why?

Last updated 2 years ago.
0

add the following code to the Item model

class Item extends Eloquent {

	protected $appends = array('cents');

	public function getCentsAttribute()
	{
		 return substr($this->attributes['price'], -2);
	}
}
Last updated 2 years ago.
0

sseffa said:

add the following code to the Item model

class Item extends Eloquent {

  protected $appends = array('cents');

  public function getCentsAttribute()
  {
  	 return substr($this->attributes['price'], -2);
  }
}

Thanks, I tried that, but it really makes no difference in this case.
I guess this could somehow have to do with autoloading of the helper functions.

Last updated 2 years ago.
0

I had some bad luck here... This issue was fixed five months ago, but my Laravel installation is older! >:(

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

popolla popolla Joined 3 Feb 2014

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.