Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skater's avatar

Calling to a model attribute function with and without optional parameters

I have in my model this function

public function getBoxAttribute() 
...
public function getSphereAttribute($absolute = true) 
...

When the function has no parameters, I can use the "short" call of the "get attribute" model: This works $model->box; and obviously this $model->getBoxAttribute();

But when the function has attributes... this does not work: $model->sphere(false) and I have to use this $model->getSphereAttribute(false);

Is it possible to name a "attribute" function in the model and call in the "short" way, no matter if they expect optional attributes or not ?

0 likes
3 replies
kokoshneta's avatar

I haven’t tried, but if you have Laravel 9, it should be possible with the new accessors:

class MyThingy {
	protected function sphere($absolute = FALSE) : Attribute {
		return Attribute::get(function($value) use ($absolute) {
			...
		});
	}
}

In Laravel 8, I think you’d have to jump through quite a few hoops to make it work.

skater's avatar

@kokoshneta Thank you, but I hope there's other method ... that would make the model very dirty

kokoshneta's avatar

@skater Why would it make the model dirtier? Despite the anonymous function, it’s cleaner than the old way, if you ask me…

Please or to participate in this conversation.