laravel-data 0.2.0

Powerful data objects for Laravel Rust: a port of spatie/laravel-data.
Documentation

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, only and except partials and their syntax (songs.{name, artist}, songs.*), Lazy (create, when, defaultIncluded), Optional, with and additional, 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

cargo add laravel-data

Register the service provider in src/app.rs to configure the global wrap key:

Application::configure()
    .with_providers(|providers| {
        providers.add(laravel_data::DataServiceProvider);
    })

Creating data objects

use laravel_data::Data;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct SongData {
    pub title: String,
    pub artist: String,
}

impl Data for SongData {}

let song = SongData::from_value(json!({ "title": "Never Gonna Give You Up", "artist": "Rick Astley" }))?;
let song = SongData::from_source(&song_model)?;   // from anything serializable, such as a model
let songs = SongData::collect(&song_models)?;

song.to_array();
song.to_json();

For request input, use Laravel Rust's Valid<T> with validation rules on the struct.

Lazy properties

#[derive(Serialize)]
pub struct AlbumData {
    pub title: String,
    pub songs: Lazy<Vec<SongData>>,
}

impl Data for AlbumData {}

let album = AlbumData {
    title: album.title.clone(),
    songs: Lazy::create(move || songs.clone()),
};

album.to_array();                                  // {"title": "..."}: the closure doesn't run
album.include(["songs"]).to_array();               // with the songs
album.include(["songs.{title, artist}"]);          // nested lazy properties
album.include(["songs.*"]);                        // 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 with exclude(["songs"]).
  • A data object can always include or exclude properties by overriding include_properties and exclude_properties.

Only and except

only and except work on every property, lazy or not:

song.only(["title"]);
album.include(["songs.*"]).except(["songs.artist"]);

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:

#[derive(Serialize, Deserialize)]
pub struct UserData {
    pub name: String,
    #[serde(default)]
    pub nickname: Optional<String>,
}

Mapping property names

Use serde's attributes, PHP's MapName, MapInputName and MapOutputName:

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserData {
    pub first_name: String,
}

Appending properties

impl Data for UserData {
    fn with(&self) -> Map<String, Value> {
        let mut with = Map::new();
        with.insert("endpoint".to_owned(), json!(format!("/users/{}", self.id)));
        with
    }
}

user.additional(json!({ "role": "admin" }));

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:

impl Data for AlbumData {
    fn allowed_request_includes() -> Option<Vec<&'static str>> {
        Some(vec!["songs"])   // None allows every include; the default allows none
    }
}

pub async fn show(request: Request) -> laravel::http::Response {
    album.to_response(&request)
}

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 laravel_data::DataCollection;

albums.include(["songs.title"]).to_value();
albums.to_response(&request);

Testing

cargo test --all-features

Differences from PHP

  • include, exclude, only, except, additional and wrap return a Transformation instead of changing the object.
  • Creating data objects uses serde (from_value, from_source, collect); validation is Laravel Rust's Valid<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_value and responses (plain serde_json::to_string), a lazy property that isn't included by default serializes as null.

Not yet ported (planned for a later release)

  • Paginated collections with links and meta, and CursorPaginatedDataCollection.
  • Lazy::whenLoaded (relations), Lazy::inertia and Lazy::closure, and auto lazy.
  • Computed properties, casts, transformers, rule inferring, validation attributes and validateAndCreate, magic from* methods, injected property values, data factories, TypeScript generation and the make:data command.

License

MIT. See LICENSE.md.