Laravel Eloquent模型加Swagger注解后fullname属性失效求助
解决Laravel模型添加OpenAPI注解后访问器失效的问题
问题根源
你显式声明了private $firstname和private $lastname私有属性,但Eloquent模型的数据库字段并非存储为类的私有属性,而是通过魔术方法从内部$attributes数组读取值。直接声明私有属性后,$this->firstname会优先访问这个未被Eloquent赋值的私有变量,而非数据库字段值,导致返回null,最终让fullname访问器失效。
修复方案
方案一:保留属性级注解(简化版)
移除模型中显式声明的私有属性,直接保留OpenAPI注解即可,Swagger工具依然能识别这些注解生成文档:
class User extends Authenticatable { ... protected $appends = [ 'fullname' ]; #[OA\Property(type: "string", example: "John")] #[OA\Property(type: "string", example: "Doe")] /** * @return Attribute */ public function fullname(): Attribute { return new Attribute( get: fn () => trim($this->firstname . ' ' . $this->lastname), ); } }
方案二:使用类级Schema注解(更规范)
将所有字段的OpenAPI注解统一放在模型的文档块中,更符合OpenAPI的Schema定义规范:
/** * @OA\Schema( * @OA\Property(property="firstname", type="string", example="John"), * @OA\Property(property="lastname", type="string", example="Doe"), * @OA\Property(property="fullname", type="string", example="John Doe") * ) */ class User extends Authenticatable { ... protected $appends = [ 'fullname' ]; /** * @return Attribute */ public function fullname(): Attribute { return new Attribute( get: fn () => trim($this->firstname . ' ' . $this->lastname), ); } }
验证效果
修改完成后,$this->firstname和$this->lastname会正常读取数据库字段值,fullname访问器恢复工作,同时OpenAPI注解依然能被Swagger工具识别并生成正确的接口文档。
内容的提问来源于stack exchange,提问作者houssem
相关产品推荐
相关产品推荐

