Laravel
Eloquent models
PHP autodoc-laravel understands your database models and uses them to accurately document your API responses and TypeScript types.
Example
return response()->json([
'user' => User::find(1),
]);
To see examples of implicit route model binding, check out the Routing section.
Relations
Currently these types of relations are supported: BelongsTo, BelongsToMany, HasMany, HasManyThrough, HasOne, HasOneThrough.
To correctly read your relation types, there must be a return type PHPDoc annotation with related model template type specified above the relation method. Example:
/**
* @return HasMany<Document, $this>
*/
public function documents(): HasMany
{
return $this->hasMany(Document::class);
}
If you are using a tool like PHPStan/Larastan, chances are you already have these annotations in place.
Serialization
The EloquentModel extension, provided by PHP autodoc-laravel, prevents reading properties like autodoc would from a regular class, but instead will check for a toArray method, and if not found on the model, will read properties from columns of the associated database table.
This extension also offers support for casts, appended and visible/hidden properties.
Setting attributes
Attributes set on a model instance with setAttribute are tracked, whether the call stands alone or is chained:
$planet = Planet::firstOrFail();
$planet->setAttribute('display_name', 'Gaia');
return [
'name' => $planet->display_name,
'score' => Planet::firstOrFail()->setAttribute('score', 42)->score,
];
Both display_name and score appear in the documented response with the types of their assigned values, and setting extra attributes does not disturb resolution of the model's real columns.
Set attributes are also kept when the whole model is serialized - returned from a route directly or converted with toArray() - following Laravel's serialization rules:
- Keys excluded by the model's
$hidden/$visiblelists are not added to the output. - Keys backed by a cast, a date attribute or a set mutator keep the column's resolved type instead of the assigned value, since Laravel transforms such values on write.
- JSON column writes like
setAttribute('options->theme', 'dark')do not produce a top-level attribute.
Attributes set inside a collection each() callback are merged into the collection's item type - see the Collections section.
Offline mode
By default, model attribute shapes are read from the columns of the associated database table. If the environment running autodoc has no database access - CI, for example - you can set laravel.offline_mode to true:
'laravel' => [
'offline_mode' => true,
],
In this mode autodoc never connects to the database and infers model attributes from casts, dates, appends, accessors and PHPDoc @property tags only. Columns that exist solely in the database schema, with none of those sources backing them, will be missing from the generated shapes.