Laravel eloquent model and swagger openApi annotation issues
P粉178894235
P粉178894235 2023-12-31 19:41:40
0
1
525

So, in my user model, I have a function fullname that returns the user's full name:

/**
 * @return Attribute
 */
public function fullname(): Attribute
{
    return new Attribute(
        get: fn () => trim($this->firstname . ' ' . $this->lastname),
    );
}

It works as expected, now I want to add OpenAPI annotation on my model: This is what I did:

class User extends Authenticatable
{
    ...
       
    protected $appends = [
        'fullname'
    ];

    #[OAProperty(type: "string", example: "Jhon")] 
    private $firstname; 

    #[OAProperty(type: "string", example: "Doe")] 
    private $lastname;
    
    /**
     * @return Attribute
     */
    public function fullname(): Attribute
    {
        return new Attribute(
            get: fn () => trim($this->firstname . ' ' . $this->lastname),
        );
    }
}

At this point the feature no longer works as expected:

$this->firstname and $this->lastname

No longer returns null value.

Question: I want to keep the comments but also make the function work.

Note: If you access your user via eloquent ex. ( User::all()->first(); ) We got the first and last name but not the full name, thanks for the help

P粉178894235
P粉178894235

reply all(1)
P粉955063662

https://github.com/DarkaOnLine/L5-Swagger/issues/157

According to this question: Defining attributes on the model will cause many eloquent problems

I found 3 ways to solve this problem:

Option 1: You need to do the least amount of refactoring

Keep comments and remove attribute definitions, for example: this:

#[OA\Property(type: "string", example: "Jhon")] 
private $firstname; 

#[OA\Property(type: "string", example: "Doe")] 
private $lastname;

will become this:

#[OA\Property(property: "firstname", type: "string", example: "Jhon")] 
#[OA\Property(property: "lastname",type: "string", example: "Doe")]

Note: The attribute or annotation must be located above the variable or function, otherwise an error will occur.

Option 2: Cleaner, but adds more work

Place your open API declaration elsewhere. For example:

Option 3: This is what I use

Add your properties to the schema declaration Example:

#[OA\Schema(schema: "IUser", properties: [
    new OA\Property(property: "firstname", type: "string", example: "Jhon"),
    new OA\Property(property: "lastname",type: "string", example: "Doe")
])]

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template