What does a JSON:API resource handle regarding serialization in Laravel 13?

In Laravel 13, the first-party JsonApiResource handles serialization by automatically transforming your Eloquent model into a spec-compliant JSON:API document structure. It takes over the mechanical obligations of the specification, meaning you don not manually build the data wrapper or manage relationship arrays yourself.

What the Serialization Handles Automatically?

When you return a JsonApiResource, the framework is serialization layer performs several key tasks behind the scenes:

Document Structuring: It wraps your resource data inside the standard top-level data object, ensuring the output adheres to the JSON:API document format.
Resource Identification: It automatically resolves the type and id for the resource object. By default, the type is derived from the resource class name, and the ID is pulled from the model is route key (though you can override this with toType and toId methods).
Attribute Resolution: It serializes the attributes you define into the attributes member of the resource object, separating them from relationships as required by the spec.
Relationship Serialization: It converts defined relationships into resource identifier objects (with type and id) within the relationships key. If the client requests related data via the ?include= query parameter, it also populates the top-level included array with the full resource objects for those relations.
Sparse Fieldsets: It respects the ?fields[type]=... query parameter, allowing clients to request only specific attributes, and the serializer filters the output accordingly.
Header Management: It sets the correct Content-Type: application/vnd.api+json header on the response automatically.

Example: Defining Serialization Rules

Instead of a single toArray method, you declare your serialization intent using specific properties or methods on the resource class.

namespace AppHttpResources;

use IlluminateHttpResourcesJsonApiJsonApiResource;

class PostResource extends JsonApiResource
{
   // Attributes to serialize into the "attributes" member
   public $attributes = [
        notitle ,
        body ,
        created_at ,
   ];

   // Relationships to serialize into the "relationships" member
   public $relationships = [
        author ,
        comments ,
   ];
}

When you return new PostResource($post) from a route, the SDK handles the rest. For instance, a request to /api/posts/1?include=author will result in a JSON:API document where the post is attributes are serialized, the author is represented as a relationship identifier, and the full author data is placed in the included array—all without you manually constructing that structure in the resource class.

18 Views