Data for Laravel Rust
laravel-data is a port of spatie/laravel-data to Laravel Rust. Data objects describe your data once and serve as API resources: lazy properties that are only included when asked for, partial includes from the query string, additional properties, wrapping and collections.
[!NOTE] This is a community port maintained by Rivervo. It is not an official Spatie package. It follows spatie/laravel-data 4.23.1: the same
include,exclude,onlyandexceptpartials and their syntax (songs.{name, artist},songs.*),Lazy(create,when,defaultIncluded),Optional,withandadditional, wrapping, request partials and response statuses, with Rust naming. In Rust, serde and Laravel Rust's validation already do what PHP's casts, mappers and validation attributes do, so this port focuses on data objects as resources. All credit for the design goes to Spatie and the package's contributors.
- Installation
- Creating data objects
- Lazy properties
- Only and except
- Optional properties
- Mapping property names
- Appending properties
- Responses and wrapping
- Collections
- Testing
- Differences from PHP
- Not yet ported (planned for a later release)
- License
Installation
cargo add laravel-data
Register the service provider in src/app.rs to configure the global wrap key:
configure
.with_providers
Creating data objects
use Data;
use ;
let song = from_value?;
let song = from_source?; // from anything serializable, such as a model
let songs = collect?;
song.to_array;
song.to_json;
For request input, use Laravel Rust's Valid<T> with validation rules on the struct.
Lazy properties
let album = AlbumData ;
album.to_array; // {"title": "..."}: the closure doesn't run
album.include.to_array; // with the songs
album.include; // nested lazy properties
album.include; // every lazy property of the songs
Lazy::when(|| user.is_admin, || ...)is only included when the condition holds, and can't be included otherwise.Lazy::create(|| ...).default_included()is included unless excluded withexclude(["songs"]).- A data object can always include or exclude properties by overriding
include_propertiesandexclude_properties.
Only and except
only and except work on every property, lazy or not:
song.only;
album.include.except;
Optional properties
Optional<T> is left out of the output when it's missing. Give the field #[serde(default)] so missing input deserializes as Optional::Missing:
Mapping property names
Use serde's attributes, PHP's MapName, MapInputName and MapOutputName:
Appending properties
user.additional;
Responses and wrapping
to_response(&request) sends the data as JSON with 201 for a POST and 200 otherwise, as PHP does, and applies the ?include=, ?exclude=, ?only= and ?except= partials the data object allows:
pub async
A transformation (what include, only, additional and the others return) is a response too. Responses are wrapped in the DataConfig::wrap key (None by default), a data object's default_wrap, or .wrap("data"); .without_wrapping() turns it off.
Collections
A Vec of data objects is a collection, with the same partials for every item:
use DataCollection;
albums.include.to_value;
albums.to_response;
Testing
cargo test --all-features
Differences from PHP
include,exclude,only,except,additionalandwrapreturn aTransformationinstead of changing the object.- Creating data objects uses serde (
from_value,from_source,collect); validation is Laravel Rust'sValid<T>. - A request partial must be listed in
allowed_request_*exactly as requested (or*). PHP also checks a nested partial against the nested data class's own allowed list. - Outside
to_array,to_valueand responses (plainserde_json::to_string), a lazy property that isn't included by default serializes asnull.
Not yet ported (planned for a later release)
- Paginated collections with
linksandmeta, andCursorPaginatedDataCollection. Lazy::whenLoaded(relations),Lazy::inertiaandLazy::closure, and auto lazy.- Computed properties, casts, transformers, rule inferring, validation attributes and
validateAndCreate, magicfrom*methods, injected property values, data factories, TypeScript generation and themake:datacommand.
License
MIT. See LICENSE.md.