Define a resource schema
developSchemas are the core of Laravel JSON:API. They define how your Eloquent models are exposed via the API. You define fields (including relationships), filters, and pagination within a class extending Schema.
Key components of a schema include:
$model: The Eloquent model class this schema represents.fields(): An array of field definitions using types likeID,Str,DateTime,BelongsTo,HasMany, andBelongsToMany.filters(): An array of available filters (e.g.,WhereIdIn,WhereIn).pagination(): Defines the pagination strategy (e.g.,PagePagination).
class PostSchema extends Schema
{
/**
* The model the schema corresponds to.
*
* @var string
*/
public static string $model = Post::class;
/**
* The maximum include path depth.
*
* @var int
*/
protected int $maxDepth = 3;
/**
* Get the resource fields.
*
* @return array
*/
public function fields(): array
{
return [
ID::make(),
BelongsTo::make('author')->type('users')->readOnly(),
HasMany::make('comments')->readOnly(),
Str::make('content'),
DateTime::make('createdAt')->sortable()->readOnly(),
DateTime::make('publishedAt')->sortable(),
Str::make('slug'),
BelongsToMany::make('tags'),
Str::make('title')->sortable(),
DateTime::make('updatedAt')->sortable()->readOnly(),
];
}
/**
* Get the resource filters.
*
* @return array
*/
public function filters(): array
{
return [
WhereIdIn::make($this),
WhereIn::make('author', 'author_id'),
];
}
/**
* Get the resource paginator.
*
* @return Paginator|null
*/
public function pagination(): ?Paginator
{
return PagePagination::make();
}
}