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

fcolecumberri's avatar

make accessor aware of api call/serialization to avoid translation when interacting with api

I have an enum type, so when the model access the enum with blade, I have the __() function on the accessor, this makes the translation of the enum automatically and avoid having special case codes (as it should). However this messes up with the api interface. So I was wondering if there is a way to make the accessor aware of the context.

I want to do something like this:

public function getFooAttribute($value){
	if(/* api call */)
		return $value;
	return __("FooType.$value");
}

I know at the controller I can do $request->is('api/*') but here I have no access to the Request instance.

I think this could also work with something like:

public function getFooAttribute($value){
	if(/* serializing */)
		return $value;
	return __("FooType.$value");
}
0 likes
1 reply
martinbean's avatar

@fcolecumberri Your model should not have any knowledge of the context its being used in. A model is data and business logic.

If you need to invoke a model’s accessor, do it in an Eloquent API resource class:

public function toArray($request)
{
    return [
        // Other model attributes
        'some_key' => $this->resource->name_of_accessor,
    ];
}

Please or to participate in this conversation.