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
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:
will become this:
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: