You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:35:27