league/fractal
League Fractal is a transformation/presentation layer for API output (JSON/YAML). Define consistent serializers and transformers, type-cast fields, include related resources, and handle pagination—keeping response schemas stable as your data changes.
Start by installing the package via Composer and understanding Fractal’s core concepts: Transformer, Resource, Manager, and Serializer. The immediate use case is transforming Eloquent models or plain arrays into consistent JSON for APIs.
composer require league/fractal.Transformer class (extend TransformerAbstract) to define how your data maps to output.Manager to create a Resource (e.g., new Item($model, new YourTransformer())) and serialize with toJson() or toArray().ArraySerializer, DataArraySerializer, or JsonApiSerializer) based on your API format needs.User model into JSON without exposing internal DB fields or inconsistent types.transform() to return a standardized schema—use include methods to conditionally embed relationships (e.g., includePosts() for /users?include=posts).Manager::parseIncludes('posts:limit(10):order(-created_at)'), enabling flexible, client-controlled expansion of nested data.Collection::setPaginator(), and Fractal auto-generates pagination metadata and links in JSON-API/Array formats.parseFieldsets() to let clients request only needed fields (?fields[users]=name,email), reducing payload size.null values with Resource::null() or scalars via Primitive—avoiding null collapsing in output.meta structure), or mix in hooks like shouldSerializeNull().getCurrentScope() returns null. Capture it within the transformer (e.g., in transform()) if needed—otherwise, rely on include* methods that receive scope parameters.setMeta() adds top-level metadata, while attributes (in transform()) contain resource fields. In JSON-API, attributes must be an object—not an array—even if empty.setPaginator() before serialization. Non-paginated collections omit pagination metadata unless you explicitly add it.transform() (e.g., (bool) $model->active) to avoid inconsistent JSON booleans/strings.limit(5) is parsed by your transformer logic—not Fractal itself. Validate or sanitize these if来自 untrusted clients (e.g., enforce max limits).How can I help you explore Laravel packages today?