To start, you could just throw this code into a custom function in your User Model and use that to look it up. Maybe something like User::findOrFailApi($id);. It may still be messy, but at least you are hiding it in one place.
Edit: Since you are casting this to json or an array, it will have the toJson and toArray methods that you can override in your user model.
public function toJson($options = 0) {
$this->setAttributeVisibility(); // set visibility stuff here
return parent::toJson();
}
And the same with toArray().
public function toArray() {
$this->setAttributeVisibility(); // set visibility stuff here
return parent::toArray();
}
Then add all your checks:
public function setAttributeVisibility()
{
...
}